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
}
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.
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.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With