首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >QMainWindow 和 QWidget 设置layout

QMainWindow 和 QWidget 设置layout

作者头像
_gongluck
发布2018-03-09 15:26:17
3.4K0
发布2018-03-09 15:26:17
举报

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

这样就可了。

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

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();
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年05月17日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • void QWidget::setLayout(QLayout * layout)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档