检查是否创建/分配了QDialog类型的变量

时间:2017-12-20 09:04:30

标签: qt

我有一个如下的头文件:

testDialog* test; //Here testDialog is a QDialog type

这是我的.cpp文件:

test = new testDialog(m_dialog);

我想在执行之前检查对话框是否已创建/分配给test

所以我在cpp文件中执行了以下操作:

void testApp::init() {
if (somethingelse) {
    test = new testDialog(m_dialog);
    mFlag = true;
}
}

这里我重写了exec函数:

int testApp::exec()
{
    if (mFlag) {
        test->show();
        test->activateWindow();
        mFlag = false;
    }
    return testApp::exec();
}

这很有效。但我想知道如果不使用旗帜是否可行。直接检查是否在test中创建/分配了新的对话框类型。谁能提出任何建议?谢谢。

2 个答案:

答案 0 :(得分:1)

你可以检查:if(test == Q_NULLPTR)

在.h文件中创建以下步骤:testDialog * test = Q_NULLPTR;

void testApp::init() {
    if (test == Q_NULLPTR) {
        test = new testDialog(m_dialog);
        //mFlag = true;
    }
}

int testApp::exec()
{
    if (test) {
        test->show();
        test->activateWindow();
        //mFlag = false;
    } else { //if you want
        test = new testDialog(m_dialog);
        this->exec(); // or test->show(); test->activeWindow();
    }

    return testApp::exec();
}

void testApp::deleteTest() {
    delete this->test;
    this->test = Q_NULLPTR;
}

答案 1 :(得分:0)

您只需测试if ( test != NULL && test->isVisible() )

如果对话框已创建且现在可见,则会对true进行评估(请注意,如果您调用了show()但该应用尚未显示,则可能会返回false)。

如评论所述,请确保在类初始化时将test设置为NULL。

相关问题