如何检查是否存在动态属性

Lio*_*ing 6 c++ qt qobject qt5 qtcore

我使用setProperty函数将动态属性设置为object.
但我想在其他地方检查创建的属性是否存在.

我做了什么:
设置属性时:

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);
Run Code Online (Sandbox Code Playgroud)

检查属性是否存在时:

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

Rei*_*ica 8

如果该属性不存在,则该QObject::property方法返回无效的变体.这是记录在案的.

从而:

QVariant filePath = activeWindow->property("filePath");
if (filePath.isValid()) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

旁注:比较任何东西true要么是完全多余的,要么是某处破碎设计的标志.你不应该... == true,也没有... == false在你的代码的任何地方.