How to find specific Qt.ItemFlag occurrence into custom Qt.ItemFlags instance in PyQt?

后端 未结 1 638
青春惊慌失措
青春惊慌失措 2021-02-02 01:56

I have a QTreeWidget with QTreeWidgetItems. Method QTreeWidgetItem.flags() returns me Qt.ItemFlags instance.

The Qt.ItemFlags type is a typedef for QFlags

1条回答
  •  盖世英雄少女心
    2021-02-02 02:21

    Like many of the "flags" and "attributes" in Qt, ItemFlags uses bit masks to combine multiple options into a single value. This can be tested using bitwise operators.

    Here is how you would check if the item is checkable:

    flags = item.flags()
    if flags & QtCore.Qt.ItemIsUserCheckable:
        print "is checkable", item, item.text(column)
    

    Bitwise Masking

    It works like this:

    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.ItemIsTristate       64  The item is checkable with three separate states.
    

    So the value will be some combination of these values. Lets say it is Selectable, Editable, and enabled. For simplicity I will just use the numeric values instead of the flags. We combine them with a logical OR:

    flags = 1 | 2 | 32
    # 35
    

    And to test the presence of a value we use a logical AND:

    # is it editable?
    flags & 2
    # 2 # would evaluate to True
    
    # is it checkable?
    flags & 16
    # 0 # would evaluate to False
    

    You could also toggle the flags state in the maks using an XOR operation.

    # toggle off the editable flag
    flags ^= 2
    # toggle on the editable flag
    flags ^= 2
    

    0 讨论(0)
提交回复
热议问题