在QT纯代码做UI界面时在QMainWindow中添加控件和布局,均无法显示问题

今天在用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);//最后把布局塞进中心窗口中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值