qt 创建第二个ui_从代码访问在UI中创建的Qt布局?

This is probably the dumbest problem I have ever had, but I am extremely confused. I am trying to get started with layouts, but for some reason cannot figure this one out.

I have tried adding a QGridLayout via the .ui file by just drag dropping it into my project. As I want to populate the grid with widgets upon loading, I have tried to use the "gridLayout" object in the "mainwindow.h" file both before/after the this->setupui() is called.

As I couldn't figure that out, I opted to just try creating it from scratch using code, and added the following to the main.cpp file instead. This did not display either, so I am wondering how on earth I can populate the grid when the form loads.

#include

#include

#include "mainwindow.h"

int main(int argc, char *argv[])

{

QApplication app(argc, argv);

MainWindow w;

QGridLayout *grid = new QGridLayout;

QLabel *label1 = new QLabel("test");

QLabel *label2 = new QLabel("test 2");

grid->addWidget(label1, 0, 0);

grid->addWidget(label2, 0, 1);

w.setLayout(grid);

w.show();

return app.exec();

}

解决方案

Assuming, you have simply set a QGridLayout in QtDesigner to your centralWidget in the MainWindow like this:

you can access it in your MainWindow code in that way with the correct object name (here it is gridLayout):

MainWindow::MainWindow(QWidget *parent) :

QMainWindow(parent),

ui(new Ui::MainWindow)

{

ui->setupUi(this);

ui->gridLayout->addWidget(new QLabel("hello world"),0,0);

}

If you have set a layout in QtDesigner or in code and you want to change the layout, QWidget won't let you install another one and you will get an error message like this:

QWidget::setLayout: Attempting to set QLayout "" on MainWindow "MainWindow", which already has a layout

In this case you have to delete the existing layout at first and then install the new one like in your code above.

If you want to access the layout in your main function you can achieve this by the QObject::findChild function like this:

int main(int argc, char *argv[])

{

QApplication a(argc, argv);

MainWindow w;

QGridLayout *gridLayout = w.findChild("gridLayout");

Q_ASSERT(gridLayout);

gridLayout->addWidget(new QLabel("hello, the second"));

w.show();

return a.exec();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值