您需要为新窗口和要放入其中的内容创建类标记变量,而不是new
在函数中使用关键字创建对象本身,因为如果您仅在函数中创建所有这些,那么它们将在堆栈,您应该知道在函数返回/完成后,该函数的堆栈将被删除(以及您的新窗口和上面的东西)。
在 windowManager 头文件中包含要使用的类的头文件:
#include <QDialog>
#include <QLineEdit>
#include <QLabel>
#include <QVBoxLayout>
然后将标签变量添加到私有部分:
private:
QDialog *window;
QLineEdit *question;
QLabel *label;
QVBoxLayout *layout;
在按钮的点击事件中设置标签变量,并创建 UI 设置:
void windowManager::addQuestionDialog()
{
window = new QDialog();
question = new QLineEdit();
label = new QLabel();
layout = new QVBoxLayout();
layout->addWidget(question);
layout->addWidget(label);
window->setLayout(layout);
window->resize(200,200);
window->setWindowTitle(QObject::trUtf8("Kérdés bevitele..."));
window->show();
}
也不要忘记在这里你应该使用->
而不是.
调用函数,因为这些标签变量是指针。这也是为什么您不需要使用&
运营商来获取他们的地址的原因。
还要记住,您应该删除这些对象,因为 C++ 不会自动为您删除这些对象。你应该delete
一切你new
。这样做的一个好地方是在你的windowManager
类的析构函数中。在尝试删除它们之前,只需检查标签变量是否不NULL
存在(如果有对象),否则可能会出现错误。
更好的解决方案是传递一个父指针作为构造函数的参数,这样Qt会在它们关闭时删除它们,因为如果父对象被销毁,子对象也将被销毁。
另外,您不必手动设置对象的去向,因为 Qt 现在将它从层次结构中(在某些情况下)。
在这种情况下,您的按钮的单击事件函数将如下所示:
void windowManager::addQuestionDialog()
{
window = new QDialog(this);
question = new QLineEdit(window);
label = new QLabel(window);
layout = new QVBoxLayout(window);
//The following two lines are optional, but if you don't add them, the dialog will look different.
layout->addWidget(question);
layout->addWidget(label);
window->resize(200,200);
window->setWindowTitle(QObject::trUtf8("Kérdés bevitele..."));
window->show();
}