QMainWindow 和 QWidget 设置layout

来源:互联网 发布:苹果anywhere软件 编辑:程序博客网 时间:2024/05/18 20:09
给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


[cpp] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. widget = new QWidget();  
  2. this->setCentralWidget(widget);  
  3. cbox = new QCheckBox(this);  
  4. cbox->setText("choose");  
  5. cbox->setChecked(false);  
  6. button = new QPushButton(this);  
  7. QVBoxLayout *layout = new QVBoxLayout(this);  
  8.   
  9. layout->addWidget(cbox);  
  10. layout->addWidget(button);  
  11.   
  12. widget->setLayout(layout);  

这样就可了。


/******************************************************************************************************/

void QWidget::setLayout(QLayout * 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();



原创粉丝点击