QTableWidget设置Item不可编辑状态

1. 背景

使用 QTableWidget时想设置第一列不可编辑,而不是整个QTableWidgetItem不可编辑,遂查找资料,有些心得。 

2. 设置方法

​给该列的每一个Item设置Flags,其实只要不是Qt::ItemIsSelectable,应该都可以做到不可编辑状态(没有一 一尝试)。

QTableWidgetItem *item0 = new QTableWidgetItem(QString::number(timeInterval));
item0->setFlags(Qt::ItemIsEnabled);//此处是关键
ui.tableWidget->setItem(row, 0, item0);

3. 进一步了解

在Qt Assitant中查看Qt::ItemFlags,结果如下:



enum Qt::ItemFlag
flags Qt::ItemFlags

This enum describes the properties of an item:

Constant

Value

Description

Qt::NoItemFlags

0

It does not have any properties set.

Qt::ItemIsSelectable

1

It can be selected.

Qt::ItemIsEditable

2

It can be edited.

Qt::ItemIsDragEnabled

4

It can be dragged.

Qt::ItemIsDropEnabled

8

It can be used as a drop target.

Qt::ItemIsUserCheckable

16

It can be checked or unchecked by the user.

Qt::ItemIsEnabled

32

The user can interact with the item.

Qt::ItemIsAutoTristate

64

The item's state depends on the state of its children. This enables automatic management of the state of parent items in QTreeWidget (checked if all children are checked, unchecked if all children are unchecked, or partially checked if only some children are checked).

Qt::ItemIsTristate

ItemIsAutoTristate

This enum value is deprecated. Use Qt::ItemIsAutoTristate instead.

Qt::ItemNeverHasChildren

128

The item never has child items. This is used for optimization purposes only.

Qt::ItemIsUserTristate

256

The user can cycle through three separate states. This value was added in Qt 5.5.

 这是枚举类型,列出了很多值。再用qDebug()分别输出一下设置后的Flags和默认的Flags。

QTableWidgetItem *item1 = new QTableWidgetItem(QString::number(speedValue));
qDebug()<< item0->flags();
qDebug()<< item1->flags();

 结果如下,默认的flags居然有6个。

QFlags<Qt::ItemFlag>(ItemIsEnabled)
QFlags<Qt::ItemFlag>(ItemIsSelectable|ItemIsEditable|ItemIsDragEnabled|ItemIsDropEnabled|ItemIsUserCheckable|ItemIsEnabled)

 不难发现,默认的设置如果转成二进制值为0 0011 1111(十进制63),而我们设置的为0 0010 0000(在表中不能被选中,那也肯定不能被用户编辑了)。所以下面两行代码等价:

item0->setFlags(Qt::ItemIsEnabled);
item0->setFlags((Qt::ItemFlag)32);//使用数字描述flags

比如默认的设置是多个组合,我们就可以用63代替。写代码时可以根据选择,灵活使用数字,减少代码书写。

查看Qt助手时,还发现了

Note that checkable items need to be given both a suitable set of flags and an initial state, indicating whether the item is checked or not. This is handled automatically for model/view components, but needs to be explicitly set for instances of QListWidgetItem, QTableWidgetItem, and QTreeWidgetItem
.

 说是QTableWidgetItem需要显式设置,应该是建议我们根据需要自己设置。

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值