Question

In a QTableWidget i want to display all values only with two decimals places. For that I subclassed QTableWidgetItem.

class MyCell(QTableWidgetItem):
    def __init__(self, *args):
        QTableWidgetItem.__init__(self, *args)

    def clone(self):
        return MyCell()

    def data(self, role):
        t = QTableWidgetItem(self).data(role)
        if role == 0:
            if t.type() != 0:
                try:
                    a, b = str(t.toString()).split('.')
                    return QVariant( ".".join([a,b[:2]]))
                except:
                    return t
         return t

I read the documentation and was thinking that I can use something like:

class MyDialog(QDialog):
    def __init__(self, parent=None):
         super(MyDialog, self).__init__(parent)

         self.table = QTableWidget()
         acell = MyCell()
         self.table.setItemPrototype(acell)

         self.table.setRowCount(5)
         self.table.setColumnCount(5)
         ....

But this crashes more or less randomly. When I use the method self.table.setItem it works without problem. Any hints are appreciated.

Was it helpful?

Solution

There are two issues here. One may be a problem with your code, the other may be a bug in PyQt.

In your data() method implementation, you probably meant to write this:

def data(self, role):
    t = QTableWidgetItem.data(self, role)
    ...

This calls the superclass's data() method rather than creating a new item and calling its data method.

When you set up your dialog, you may need to keep a reference to your item prototype:

def __init__(self, parent=None):
    super(MyDialog, self).__init__(parent)

    self.table = QTableWidget()
    self.acell = MyCell()
    self.table.setItemPrototype(self.acell)

Although the Qt documentation says that ownership of the prototype is passed to the table widget, the PyQt bindings don't appear to do this, so you will need to prevent the prototype from being garbage collected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top