如果你在主窗口进行Qt布局的时候,显示出现如下
是不是很绝望,查边网上各种布局显示,发现到头来一场空,绝望!!
好了进入正题,这是因为主窗口以及有了自己默认的Layout,你在自己添加也是没有用的(喊破喉咙也没用)
但是总得有解决办法,他不让我们布局,我们凿一个洞就是了,这个锤子就是
QMainWindow::setCentralWidget(QWidget *widget)
Sets the given widget to be the main window's central widget.(其实就是凿洞),现在工具有了
就差东风了:下面我带你火烧赤壁
1、在主窗口的构造函数中
建立一个布局
QWidget *widget=new QWidget(this);
this->setCentralWidget(widget);
2、设置自己的布局
QVBoxLayout *btnlayout = new QVBoxLayout(this);//建立垂直显示
这里面进行自己的布局定义
比如建立laber 建立btn 等
3、添加到定义的wight里面
centralWidget()->setLayout(btnlayout);
下面是我提供的参考例程:
在主窗口构造函数中添加如下代码
QWidget *widget=new QWidget(this);
this->setCentralWidget(widget);
this->resize(240,180);
QPushButton *btn = new QPushButton(this);
btn->setText("想要宝藏嘛");
QVBoxLayout *btnlayout = new QVBoxLayout(this);//建立垂直显示
btnlayout->setDirection(QBoxLayout::TopToBottom);
QLabel *Label = new QLabel(this);
Label->setText("恭喜进来快点他!!!");
btnlayout->addWidget(Label);
btnlayout->addWidget(btn);
centralWidget()->setLayout(btnlayout);
下面附上我的结果