QMainWindow 和 QWidget 设置layout

给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


  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();



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值