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(ItemIsEnabled)
QFlags(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需要显式设置,应该是建议我们根据需要自己设置。

你可能感兴趣的:(Qt,qt)