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

问题描述 投票:1回答:2

我有一个如下的头文件:

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中创建/分配了新的对话框类型。谁能提出任何建议?谢谢。

qt
2个回答
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;
}

0
投票

你可以简单地测试if ( test != NULL && test->isVisible() )

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

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

© www.soinside.com 2019 - 2024. All rights reserved.