QObject的setUserData和setProperty——Qt_xiaopei_yan的博客-CSDN博客前言很多时候需要界面存储一些数据或信息,这样可以根据这些数据或信息来了解或获取点什么。可以说给界面增加一个标记,让我们更容易辨识。我之前一直习惯给列表项QListWidgetItem或者树项QTreeWidgetItem携带一些数据,比如id,用setData来实现。所以这次就想QWidget有没有类似的方法,结果就找到了setUserData。后来在mac os中重新编译时,发现setUserData不可用了,建议用setProperty替换。用法我现在用的Qt的版本是Qt5.14 .https://blog.csdn.net/xiaopei_yan/article/details/106687148
QObjectUserData* userData(uint id) const;
void QObject::setUserData(uint id, QObjectUserData* data)
{
Q_D(QObject);
if (!d->extraData)
d->extraData = new QObjectPrivate::ExtraData;
if (d->extraData->userData.size() <= (int) id)
d->extraData->userData.resize((int) id + 1);
d->extraData->userData[id] = data;
}
QVariant property(const char *name) const;
bool QObject::setProperty(const char *name, const QVariant &value)
{
Q_D(QObject);
const QMetaObject* meta = metaObject();
if (!name || !meta)
return false;
int id = meta->indexOfProperty(name);
if (id < 0) {
if (!d->extraData)
d->extraData = new QObjectPrivate::ExtraData;
const int idx = d->extraData->propertyNames.indexOf(name);
if (!value.isValid()) {
if (idx == -1)
return false;
d->extraData->propertyNames.removeAt(idx);
d->extraData->propertyValues.removeAt(idx);
} else {
if (idx == -1) {
d->extraData->propertyNames.append(name);
d->extraData->propertyValues.append(value);
} else {
if (value.userType() == d->extraData->propertyValues.at(idx).userType()
&& value == d->extraData->propertyValues.at(idx))
return false;
d->extraData->propertyValues[idx] = value;
}
}
QDynamicPropertyChangeEvent ev(name);
QCoreApplication::sendEvent(this, &ev);
return false;
}
QMetaProperty p = meta->property(id);
#ifndef QT_NO_DEBUG
if (!p.isWritable())
qWarning("%s::setProperty: Property \"%s\" invalid,"
" read-only or does not exist", metaObject()->className(), name);
#endif
return p.write(this, value);
}