如何在PyQt5 tableWidget的相同单元格上打印多行条目?

时间:2020-04-29 21:49:34

标签: python pyqt5

如何在PyQt5 tableWidget的同一单元格中打印多行条目 (相当于当您在Excel中按Alt + Enter时的情况),因此行拆分的时间更长,但停留在同一单元格中。

我的问题与此How do I resize rows with setRowHeight有关 但是在那次询问中,他们只是在扩大行宽,我想结合self.table.resizeRowsToContents()和分割线。

例如,我有一个列表:list1 = ['A', 'B', 'C']

我想将列表的每个部分拆分到同一单元格的新行

因此它将是

而不是A, B, C
A,
B,
C

enter image description here

colomn = 1
datalist = [['A'],['B'],['C']]
for numRows in range(1,10):
    self.tableWidget.setItem(numRows, colomn, QTableWidgetItem(str(datalist)))

enter image description here

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是使用项目委托,并实现其sizeHint()paint()方法。

然后,这只是实现问题:

class ListDelegate(QtWidgets.QStyledItemDelegate):
    def sizeHint(self, option, index):
        hint = super().sizeHint(option, index)
        try:
            # try to make the string value a python object
            values = eval(index.data())
            if isinstance(values, (tuple, list)) and len(values):
                # let's assume that a blank item always has a "blank" line at least
                baseHeight = super().sizeHint(option, QtCore.QModelIndex()).height()
                # and add more line height if required
                hint.setHeight(baseHeight + option.fontMetrics.height() * (len(values) - 1))
        except:
            pass
        return hint

    def paint(self, qp, option, index):
        try:
            values = eval(index.data())
            assert isinstance(values, (tuple, list)) and len(values)
            style = option.widget.style()
            # draw a default blank item
            style.drawControl(style.CE_ItemViewItem, option, qp, option.widget)
            enabled = option.widget.isEnabled() and bool(index.data(QtCore.Qt.ItemIsEnabled))
            # then overlay its contents
            style.drawItemText(qp, option.rect, QtCore.Qt.AlignCenter, option.palette, enabled, 
                '\n'.join(', '.join(v) for v in values))
        except:
            # no data or no list contents
            super().paint(qp, option, index)

class TableTest(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtWidgets.QVBoxLayout(self)

        self.tableWidget = QtWidgets.QTableWidget(10, 2)
        layout.addWidget(self.tableWidget)
        self.tableWidget.setItemDelegateForColumn(1, ListDelegate())

        colomn = 1
        dataList = iter(tuple(ascii_uppercase) + tuple(u + l for u, l in zip(ascii_uppercase, ascii_lowercase)))
        for numRows in range(1,10):
            try:
                data = [[next(dataList)]]
                for _ in range(randrange(1, 5)):
                    if choice([0, 1, 2]):
                        data[-1].append(next(dataList))
                    else:
                        data.append([next(dataList)])
                self.tableWidget.setItem(numRows, colomn, QtWidgets.QTableWidgetItem(str(data)))
            except:
                pass

        self.tableWidget.resizeRowsToContents()
        self.resize(self.width(), 400)
相关问题