如何动态改变QMainWindow的内容 [英] How to change contents of QMainWindow dynamically

查看:194
本文介绍了如何动态改变QMainWindow的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个QMainWindow开始只有一个菜单有一个菜单有两个选项。当第一个被点击时,窗口应该填充QLabels和各种输入小部件来接收数据。当第二个选项被点击时,窗口应该填充一个QTextEdit(显然删除窗口上的任何东西在当时)

I have a QMainWindow that starts out with nothing but a menubar with a menu that has two options. When the first is clicked the window should be populated with QLabels and various input widgets to recieve data. When the second option is clicked the window should be populated with a QTextEdit(obviously removing whatever was on the window at the time)

以下是我试过的代码:

The following is code I have tried :

void OrderWindow::displayAddOrder(){
     QVBoxLayout* tlayout = new QVBoxLayout();
     QHBoxLayout* row = new QHBoxLayout();
     row->addWidget(nameLbl);
     tlayout->addLayout(row);
     qDeleteAll(children());
     delete layout();
     setLayout(tlayout);
}

这是一个有点凌乱,因为我一直在尝试各种东西。当我点击菜单选项与此代码,它只是说,应用程序已停止工作。

It's a bit messy since I've been trying various things. When I click on a menu option with this code it simply says the application has stopped working.

任何帮助将不胜感激。

推荐答案

您至少拥有以下选项:


  • 实际的小部件,并隐藏其余部分。这在两个小部件的情况下很简单,如在您的示例中。

  • Always show the actual widget, and hide the rest. This is simple in case of two widgets like in your example. You could use this technique with the observer design pattern for any number of widgets.

使用 QStackedWidget类,它基本上表现为您的自定义观察者模式实现的方式,虽然您将需要为此使用一个额外的类。

Use the QStackedWidget class which basically behaves the way as your custom observer pattern implementation would be, although you will need to use an extra class for this.

因此,我建议您编写以下代码:

Therefore, I would suggest to write the following code:

...
class QStackedWidget;
class OrderWindow
{
    ...
public:
    explicit OrderedWindow(QWidget *parent);
    ...
 private:
     QStackedWidget m_stackedWidget;
    ...
}
...



cpp



orderwindow.cpp

#include "orderwindow.h"

#include <QStackedWidget>
...

OrderWindow::OrderWindow(QWidget *parent)
    : QWidget(parent)
    ,  m_stackedWidget(new QStackedWidget(this))
{
    QWidget *firstPageWidget = new QWidget;
    QWidget *secondPageWidget = new QWidget;

    m_stackedWidget->addWidget(firstPageWidget);
    m_stackedWidget->addWidget(secondPageWidget);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(stackedWidget);
    setLayout(layout);
}

...

void OrderWindow::displayAddOrder() {
    m_stackedWidget->setCurrentWidget(nameLbl);
}

...

这篇关于如何动态改变QMainWindow的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆