Qt的QVariant类中被禁止的枚举GlobalColor、BrushStyle、PenStyle和CursorShape

在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));
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SOC罗三炮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值