【问题标题】:Adding widget to layout only works in constructor of custom class将小部件添加到布局仅适用于自定义类的构造函数
【发布时间】:2016-10-27 01:23:37
【问题描述】:

我有一个类 MainWindow 子类 QMainWindow。作为中心小部件,我有一个 QScrollArea,里面有一个 QWidget,作为我自己的自定义小部件的容器。我将 QVBoxLayout 设置为 QWidget 容器的布局,并将此布局传递给我的自定义类的构造函数,该构造函数应该动态创建我的自定义小部件类的实例并将它们添加到布局中。

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow(QWidget *parent = Q_NULLPTR);
    virtual ~MainWindow ();
private:
    QVBoxLayout mainLayout;
    QScrollArea scrollArea;
    QWidget container;
    NotificationControl control;
};

MainWindow::MainWindow (QWidget *parent) :
    QMainWindow(parent),
    container(&scrollArea),
    control(&mainLayout) {
    container.setLayout(&mainLayout);
    scrollArea.setWidget(&container);
    setCentralWidget(&scrollArea);
}

现在在我的 NotificationControl 类中,我有一个方法 addNotification:

void NotificationControl::addNotification (Notification notif) {
    qDebug() << "NotificationControl addNotification" << notif.get_app_name();
    NotificationWidget* widget = new NotificationWidget(notif);
    container->addWidget(widget);
}

调用此方法时,我得到了调试输出,但布局中没有添加任何内容。但是如果我将它添加到 NotificationControl 的构造函数的末尾......

NotificationWidget* notif = new NotificationWidget(Notification());
container->addWidget(notif);

...由于某种原因,它起作用了。我很确定问题不在于 NotificationWidget 类。出于测试目的,我做了一些更改,它实际上并没有使用传递的 Notification 对象。

可能是什么问题?

编辑:我只是注意到稍后添加小部件(不在构造函数中)会使构造函数中添加的小部件消失。

【问题讨论】:

    标签: c++ qt user-interface layout


    【解决方案1】:

    如果父小部件已经可见,则必须显式显示作为子小部件添加的任何小部件。通常,子小部件是在显示父小部件之前添加的,然后它们自己也会变得可见。但如果您稍后添加它们,则必须使它们显式可见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-28
      • 2021-12-23
      • 2012-10-23
      • 2023-01-22
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多