在Qt的qvariant.h中有这样一段话:
// These constructors don't create QVariants of the type associcated
// with the enum, as expected, but they would create a QVariant of
// type int with the value of the enum value.
// Use QVariant v = QColor(Qt::red) instead of QVariant v = Qt::red for
// example.
QVariant(Qt::GlobalColor) Q_DECL_EQ_DELETE;
QVariant(Qt::BrushStyle) Q_DECL_EQ_DELETE;
QVariant(Qt::PenStyle) Q_DECL_EQ_DELETE;
QVariant(Qt::CursorShape) Q_DECL_EQ_DELETE;
这些构造函数不能创建关于这些枚举类型的QVariant对象,但是可以将枚举值的值(也就是int整数型的值)创建int类型的QVariant对象。使用static_cast将该枚举值转换成int类型。
如果不禁用这几个构造函数,QVariant 会将这些枚举当做普通的 int,而实际这些枚举是有自己的含义的,例如,Qt::GlobalColor 其实代表一个 QColor 对象。这样的话,可能会有隐藏的 bug,因为 Qt::GlobalColor 会退化为一个普通的 int。所以,Qt 5 将这些有特殊含义的枚举的构造函数禁止掉了。
不可以使用
QVariant v = Qt::red
而是使用:
QVariant v = QColor(Qt::red)
举例:
使用QComboBox添加item数据时:
//错误,addItem传入的数据会被转换成QVariant
comboBox->addItem("CustomDashLine",Qt::CustomDashLine);
会报如下错误:
error: calling a private constructor of class 'QVariant'
qvariant.h:510:5: note: declared private here
error: attempt to use a deleted function
qvariant.h:510:5: note: 'QVariant' has been explicitly marked deleted here
错误表明:QVariant 已在此处明确标记为已删除
因为枚举值Qt::CustomDashLine属于枚举Qt::PenStyle,而上面已经说过PenStyle枚举不能创建QVariant对象。解决办法:将该枚举值转换成int类型。
comboBox->addItem(tr("CustomDashLine"),static_cast<int>(Qt::CustomDashLine));