2013-08-03 87 views
2

我有一个按钮,当它被点击时,一个新窗口显示一个QLineEdit和一个QLabel,我的按钮和函数之间的连接工作正常,但新窗口没有显示。新窗口不显示

void windowManager::addQuestionDialog(){ 
    QWidget window(&parent); 
    QLineEdit question; 
    QLabel label; 
    QVBoxLayout layout; 

    layout.addWidget(&question); 
    layout.addWidget(&label); 
    window.setLayout(&layout); 
    window.resize(200,200); 
    window.setWindowTitle(QObject::trUtf8("Kérdés bevitele...")); 
    window.show(); 

} 

回答

2

您需要为新的窗口,你想投入它,比在功能上new关键字创建对象本身的东西,创造一流的标签变量,因为如果你只是在一个函数中创建所有这些函数,而不是在堆栈中创建它们,并且你应该知道在一个函数返回/完成后,该函数的堆栈被删除(你的新窗口和它的东西也会被删除)。

包括要在窗口管理器,头文件使用类标题:

#include <QDialog> 
#include <QLineEdit> 
#include <QLabel> 
#include <QVBoxLayout> 

标签变量然后添加到私处:

private: 
    QDialog *window; 
    QLineEdit *question; 
    QLabel *label; 
    QVBoxLayout *layout; 

在您的按钮的Click事件集标签变量,并创建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(); 
} 
0

您在堆栈上创建窗口QWidget对象。因此,当对函数addQuestionDialog的调用完成时,该对象将被删除。更改代码以使用“新建”来创建新窗口小部件,并将其安排在关闭后进行删除。一些可能的解决方案是这里提出:

destructors in Qt4

+0

我已经改变了线路:QWidget的*窗口=新的QWidget(母);和window-> setAttribute(Qt :: WA_DeleteOnClose);但它仍然不显示。 – erbal