您好!
我试图在Qt中使用QTextCharFormat
方法获得data()
。
所以我以一种方式对我的数据方法进行编码,当请求的数据有DecorationRole
时,它返回QTextCharFormat
(直到现在没什么不寻常的......我猜)
问题是我无法在我的视图中将QVariant
强制转换为QTextCharFormat
:(
我会告诉你我尝试了什么以及我得到的是一个错误:
QTextCharFormat charFormat;
charFormat=model->index(i,1).data(Qt::DecorationRole).value<QTextCharFormat>();
setCurrentCharFormat(charFormat);
我也尝试过:
charFormat=model->index(1,1).data(Qt::DecorationRole).value();
和:
setCurrentCharFormat(qvariant_cast<QTextCharFormat>(model->index(1, 2).data(Qt::DecorationRole))
第一个片段给了我这个(我将从后两者中得到什么结果,我认为它们是更糟糕的解决方案)
In file included [...]
C:/Qt/Qt5.8.0/5.8/mingw53_32/include/QtCore/qmetatype.h: In instantiation of 'constexpr int qMetaTypeId() [with T = QTextCharFormat]':
C:/Qt/Qt5.8.0/5.8/mingw53_32/include/QtCore/qvariant.h:360:39: required from 'bool QVariant::canConvert() const [with T = QTextCharFormat]'
C:[...].cpp:29:58: required from here
C:/Qt/Qt5.8.0/5.8/mingw53_32/include/QtCore/qmetatype.h:1732:5: error: static assertion failed: Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object system
Q_STATIC_ASSERT_X(QMetaTypeId2<T>::Defined, "Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object system");
所以我认为它不是元类型,即使这个part of the documentation looked like I could qvariant cast something from GUI.而且这部分说明QTextCharFormat
isn't in the build in metatype enum ...
所以在这一点上,我不知道我理解错误:(。
提前致谢。
答案 0 :(得分:2)
您应该使用:
QTextCharFormat textCharFormat;
QVariant v = QVariant::fromValue(textCharFormat);
textCharFormat = v.value<QTextCharFormat>();
但是,正如您测试的那样,QTextCharFormat
未向Qt元类型系统声明,因此您需要添加:
Q_DECLARE_METATYPE(QTextCharFormat)
理想情况下,我会将它放在一个自定义标题中,我将使用它而不是Qt标题。:
// textcharformat.h
#ifndef TEXTCHARFORMAT_H
#define TEXTCHARFORMAT_H
#include <QTextCharFormat>
Q_DECLARE_METATYPE(QTextCharFormat)
#endif
现在,为什么Qt尚未将其声明为元类型,您必须向Qt开发人员询问。