Skip to content
Advertisement

How to hide checkboxes in a QTableView using python?

I’m quite new to python as well as to Qt. I would like to use the QTableView without checkboxes appearing in the tableview’s cells, but as it seems they just appear there by default. As I’ve found out so far, you just have to deactivate the Qt.ItemIsUserCheckable flag. But how am I supposed to do this? I tried to use the flags – function of the QAbstractItemModell inside a QAbstractTableModel derived model class this way:

def flags(self,index):
        return(QtCore.Qt.ItemIsEnabled| QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable)

So, what I did is: just not returning the Qt.ItemIsUserCheckable flag. This works fine e.g. for the Qt.ItemIsEditable flag making a cell editable or not (when it is not returned) but doing this with the ItemIsUserCheckable flag has no effect on the checkboxes. So my question is: how can I get rid of the checkboxes using python? Please help!

Advertisement

Answer

Well, I think I could sort this out on my own. The secret of the QTableView’s checkboxes doesn’t lie in the flag method but goes with the return value of the data-method instead. The description of the data method of QAbstractItemModel explains that you should return an invalid QVariant for those cases you donn’t want to handle. In PyQt4.11 this means that you have to return python’s None value, because None is interpretated as invalid QVariant. So all I had to do was to make sure that the data method returns None when I don’t want to handle a role:

# works for python 3.4 and PyQt4.11
def data(self,index,role):
    if not index.isValid():
        return(None)
    # for all roles you're not interested in, do nothing: i.e. return python's None which is interpreted as an invalid QVariant value
    elif role != QtCore.Qt.DisplayRole:
        return(None)
    else: 
        return(self.data[index.row()][index.column()])

Notice, that the code returns None for Qt.CheckStateRoleas this role is one of no interest to the code and that no checkboxes are displayed in the GUI. Now, if you change the data method like this:

def data(self,index,role):
    if not index.isValid():
        return(None)
    elif role == QtCore.Qt.CheckStateRole:
        return("")
    elif role != QtCore.Qt.DisplayRole:
        return(None)
    else: 
        return(self.data[index.row()][index.column()])

a string ("") is returned for the Qt.CheckStateRole which of course is not an invalid QVariant. And -surprise, surprise – checkboxes are displayed inside the TableView. Another point is that all this works without to implement the flags method I mentioned above.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement