在QMainWindow中添加子项

7

我该如何在QMainWindow的两个子部件中均等地添加两个Widget对象。

MainWindow::MainWindow(QWidget *parent)
     : QMainWindow(parent)

{   TreeArea *ta= new TreeArea(this);
    TreeArea *ta1= new TreeArea(this);
.
.
.
  TreeArea::TreeArea(QWidget *parent) :
 QWidget(parent)
{
.
.
.
3个回答

16
如e-zinc建议的,您需要使用布局。假设您想要将两个小部件插入到主窗口中:
QHBoxLayout *layout = new QHBoxLayout;

QPushButton *button1 = new QPushButton("button1");
QPushButton *button2 = new QPushButton("button2");

layout->addWidget(button1);
layout->addWidget(button2);

setCentralWidget(new QWidget);
centralWidget()->setLayout(layout);

这将水平布局小部件,您将获得以下结果:

QHBoxLayoutExample

如果你想要垂直布局它们,可以使用 QVBoxLayout。
我强烈建议阅读文档。Qt中的布局管理

我正在开发一个自定义标题栏,我认为这是最初的方法:使用布局开始将所有小部件放在那里。 - swdev

5
使用QMainWindow::setCentralWidget(QWidget *)将您自己的控件添加到中央窗口部件。

0

////////如果你想从main.cpp创建////////

    #if 0
int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    QMainWindow* MainWindow = new QMainWindow(NULL);
    QWidget*     cwidget    = new QWidget(MainWindow);
    QPushButton* button1    = new QPushButton(cwidget);
    QPushButton* button2    = new QPushButton(cwidget);

    button1->setText("Button1");
    button2->setText("Button2");

    button1->move(10, 100);
    button2->move(10, 200);

    MainWindow->setCentralWidget(cwidget);
    MainWindow->resize(400, 300);
    MainWindow->show();

    return app.exec();
}

#else
int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    QMainWindow* MainWindow = new QMainWindow(NULL);
    QWidget*     cwidget    = new QWidget(MainWindow);
    QHBoxLayout* layout     = new QHBoxLayout; //horizontal layout
    QPushButton* button1    = new QPushButton("button1");
    QPushButton* button2    = new QPushButton("button2");

    layout->addWidget(button1);
    layout->addWidget(button2);

    MainWindow->setCentralWidget(cwidget);
    MainWindow->centralWidget()->setLayout(layout); //centralWidget() is getcentralWidget()
    MainWindow->resize(400, 300);

    MainWindow->show();

    return app.exec();
}
#endif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接