#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QPushButton>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
QPushButton btn;
btn.move(100,100);
resize(600, 400);
setWindowTitle("第一个窗口asdasd");
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
如图所示,在学习QT的时候,我突发奇想,想用显式创建对象的方式来创建控件,但是运行的时候发现并没有任何显示,这是为什么呢?
这是因为,在构造函数中创建了对象以及属性,是创建在栈区的,随着函数的结束也会被销毁,相当于是一个临时变量,等于没有创建。
所以我们想要的是一个全局变量,所以可以用new的方式来创建一个在堆区的对象。
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QPushButton>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
QPushButton *btn = new QPushButton("第二个按钮", this);
btn->move(100,100);
resize(600, 400);
setFixedSize(600, 400);
setWindowTitle("第一个窗口asdasd");
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
这样再次运行我们就可以得到想要的控件了。