不使用UI文件编程
1.不生成UI文件
文件结构
①mainwindow.h
引入QPushButton头文件,声明成员变量
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
QPushButton *pushbutton;
};
#endif // MAINWINDOW_H
②mainwindow.h
QPushButton() 三种构造形式
这里调用的是QPushButton(QWidget *parent = nullptr)
代码中传的是this指针,即MainWindow;
MainWindow 继承 QMainWindow
QMainWindow 继承 QWidget
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
//为什么需要设置父对象?因为窗口需要相互联系,eg.A需要在B上显示,A需要指定父对象(这里传入this指针,指明父对象)
pushbutton = new QPushButton(this);
//设置父对象的两种方法
//1.通过析构函数传参
//2.通过setParent()方法
pushbutton->setText("我是按钮"); //继承QAbstractButton
pushbutton->setGeometry(50,150,100,50);//继承Qwidget
this->resize(800,480);//设置MainWWindow的大小
}
MainWindow::~MainWindow()
{}
实例化 pushbutton 按钮的设置文本内容 setText()方法 继承QAbstractButton;按钮位置setGeometry(50,150,100,50)方法 继承Qwidget
2.Qt的Object Tree(对象树)机制
Qt的Object Tree(对象树)机制,就是为了方便管理内存。