给QWidget或者QDialog设置布局的时候方式很简单。创建好一个布局:mainLayout,然后不停地把各个控件往mainLayout里面放,最后调用setLayout(mainLayout)就行了。 QMainWindow中使用这个方法的时候却不管用,因为QMainWindow是默认有layout的,所以再次设置layout会失效。
会出现这种提示:
QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout 这句话的意思是说,你已经给MainWindow设置过一个布局了,再设置一个会出错。 该如何给QMainWindow正确地设置布局呢 要想QMainWidget创建布局,合理的步骤应该是这样的: 第一步创建一个QWidget实例,并将这个实例设置为centralWidget: 然后创建一个主布局mainLayout,并把所需要的所有控件都往里面放(工具栏、菜单栏、状态栏除外): ...
最一步就是将widget的布局设置为mainLayout
widget = new QWidget();
this->setCentralWidget(widget);
cbox = new QCheckBox(this);
cbox->setText("choose");
cbox->setChecked(false);
button = new QPushButton(this);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(cbox);
layout->addWidget(button);
widget->setLayout(layout);
这样就可了。
/******************************************************************************************************/
Sets the layout manager for this widget to layout.
If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout.
If layout is the layout manager on a different widget, setLayout() will reparent the layout and make it the layout manager for this widget.
另一种方法:
QApplication a(argc, argv);
QMainWindow w;
w.show();
QWidget window;
QSpinBox *spinBox = new QSpinBox(&window);
QSlider *slider = new QSlider(Qt::Horizontal, &window);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(spinBox);
layout->addWidget(slider);
// window.setLayout(layout);
// w.setCentralWidget(&window);
delete w.layout();
w.setLayout(layout);
return a.exec();