How to check if a dynamic property exists

I have a function setPorpertyto set a dynamic property on an object.
But I want to check elsewhere if the created property exists or not.

What I did:
When setting 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 checking for a property:

QMdiSubWindow *activeWindow = ui->mdiArea->activeSubWindow();
if(activeWindow->property("filePath") == true){
    // code here
}
+4
source share
2 answers

If the property does not exist, the method QObject::propertyreturns an invalid option. This is documented .

In this way:

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

: - true , -. ... == true ... == false .

+5

, QVariant, , .

.

, .

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

QList<QByteArray> dynamicPropertyNames =
    ui->mdiArea->activeSubWindow()->dynamicPropertyNames();
if (dynamicPropertyNames.contains(myPropertyName))
    qDebug() << myPropertyName << "exists.";
+1

Source: https://habr.com/ru/post/1545368/


All Articles