Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 418
Lion King Avatar asked Jun 20 '14 12:06

Lion King


2 Answers

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.

like image 59
Kuba hasn't forgotten Monica Avatar answered Sep 17 '22 22:09

Kuba hasn't forgotten Monica


The problem is that you are trying to check the QVariant property directly, whereas it is not even sure if it exists in your case.

I would personally use either of the solutions below depending on your exact context in the real program.

Replace the variable placeholder with your preferred property name if you wish.

QVariant myPropertyValue =
    ui->mdiArea->activeSubWindow()->property(myPropertyName);
if(myPropertyValue.isValid())
    qDebug() << myPropertyName << "exists.";

or:

QList<QByteArray> dynamicPropertyNames =
    ui->mdiArea->activeSubWindow()->dynamicPropertyNames();
if (dynamicPropertyNames.contains(myPropertyName))
    qDebug() << myPropertyName << "exists.";
like image 27
lpapp Avatar answered Sep 17 '22 22:09

lpapp