【发布时间】: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