c++qtqt5qtcoreqobject

How to check whether or not a dynamic property exists


I have use setProperty function to set dynamic property to object.
But I want in other place to check if the property that was created is exists or not.

What I done:
When set the property:

QString fileDlg = QFileDialog::getOpenFileName(this, "Open File", "F://","Text Files(*.txt)");
QWidget *widget = new QWidget(this);
QMdiSubWindow *mdiWindows = ui->mdiArea->addSubWindow(widget);
mdiWindows->setProperty("filePath", fileDlg);

When check if property exists:

QMdiSubWindow *activeWindow = ui->mdiArea->activeSubWindow();
if(activeWindow->property("filePath") == true){
    // code here
}

Solution

  • If the property doesn't exist, the QObject::property method returns an invalid variant. This is documented.

    Thus:

    QVariant filePath = activeWindow->property("filePath");
    if (filePath.isValid()) {
      ...
    }
    

    Side note: comparing anything to true is either completely superfluous, or a sign of broken design somewhere. You should not have ... == true nor ... == false anywhere in your code.