今天在用QT框架纯代码写UI界面时,遇到在QMainWindow这个类中添加任何可视控件(例如Button、Label),都无法显示,加上布局管理器后也一样,到底是为何?
首先,对于QDialog而言,添加控件过程:
1、创建子窗口部件,如
QRadioButton *radio1 = new QRadioButton(tr("&Radio button 1"));
2、创建一个布局
QVBoxLayout *vbox = new QVBoxLayout;
3、将子窗口部件添加到布局中去
vbox->addWidget(radio1);
4、将布局设置到QDialog中去
this->setLayout(vbox);
这样,在Qdialog就可以看到子窗口部件了;但在QMainWindow中看不到???
求助google、百度,从QT Assistant 中找到这句话:
Note: Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder. 译文:不支持在没有中心小部件的情况下创建主窗口。您必须有一个中心小部件,即使它只是一个占位符。
原来QMainWindow必须要有个Central Widget.于是便给他一个中心Widget。示例代码如下:
QWidget *pCenterWidget = new QWidget; //new一个空的窗口
this->setCentralWidget(pCenterWidget );//把这个空窗口设置为QMainWindow的中心窗口
button1 = new QPushButton("One");
button2 = new QPushButton("Two");
button3 = new QPushButton("Three");
button4 = new QPushButton("Four");
button5 = new QPushButton("Five");
//把控件塞进一个布局中
layout = new QVBoxLayout;
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
layout->addWidget(button4);
layout->addWidget(button5);
QGroupBox *groupBox = new QGroupBox(tr("登录"));
groupBox->setLayout(layout);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(groupBox);
pCenterWidget->setLayout(mainLayout);//最后把布局塞进中心窗口中