Search code examples
pythonqtpyqt4qtreewidget

How to set flag for an item in a QTreeWidget?


I have a QTreeWidget which contains two columns and some rows. I would like to set a flag so that if an item in the second column is either a zero or empty, it cannot be edited. If the item clicked is not numeric, it will be shown with a red text.

My code:

def qtree_check_item(self, item, column):
    item.setFlags(QtCore.Qt.ItemIsEnabled)
    if column == 1:
        if item.text(1) != '0':
            item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
        if not item.text(1).isnumeric():
            item.setForeground(1, QtGui.QBrush(QtGui.QColor("red")))

This works if the item is zero. If I replace:

if item.text(1) != '0':

with

if item.text(1) != '':

This works for empty strings. But if I combine both using:

if item.text(1) != '0' or item.text(1) != '':

The flags are not set. What am I doing wrong?


Solution

  • I would like to set a flag so that if an item in the second column is either a zero or empty, it cannot be edited.

    You then have...

    if item.text(1) != '0' or item.text(1) != '':
        item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
    

    Now consider what happens if item.text(1) == '0'. In that case the second test item.text(1) != '' passes and the conditional as a whole passes due to the or. Likewise if item.text(1) == '' is true then the test item.text(1) != '0' will pass and the entire conditional pass as a result.

    So, you only want to set the editable flag if both...

    item.text(1) != '0' and item.text(1) != ''
    

    hold true.

    To put it another way, since item.text(1) cannot be equal to both '0' and '' at the same time the conditional...

    if item.text(1) != '0' or item.text(1) != '':
    

    is essentially...

    if True or False:
    

    which will always pass.

    (Sorry if that all seems a bit convoluted.)