简体   繁体   English

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

[英]How to print multi rows entry at the same cell of PyQt5 tableWidget?

How to print multi rows entry at the same cell of PyQt5 tableWidget (equivalent to that when u pressing Alt+Enter at Excel) so longer line splitting but stays at the same cell.如何在 PyQt5 tableWidget 的同一单元格中打印多行条目(相当于您在 Excel 中按 Alt+Enter 时的情况),以便更长的行拆分但停留在同一单元格。

My question is related to this one How do I resize rows with setRowHeight but at that questing they are just expanding row width, I want to combine self.table.resizeRowsToContents() with splitting the line.我的问题与此有关如何使用 setRowHeight 调整行的大小,但在寻求它们只是扩大行宽时,我想将self.table.resizeRowsToContents()与分割线结合起来。

for example I have a list: list1 = ['A', 'B', 'C']例如我有一个列表: list1 = ['A', 'B', 'C']

and I want to split each component of the list to the new line of the same cell我想将列表的每个组件拆分到同一单元格的新行

so instead of A, B, C it will be所以代替A, B, C它将是

A,
B,
C

在此处输入图像描述

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

在此处输入图像描述

The most simple solution is to use an item delegate, and implement both its sizeHint() and paint() methods.最简单的解决方案是使用项目委托,并实现它的sizeHint()paint()方法。

Then, it's just a matter of implementation:然后,这只是一个实现问题:

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())

        column = 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, column, QtWidgets.QTableWidgetItem(str(data)))
            except:
                pass

        self.tableWidget.resizeRowsToContents()
        self.resize(self.width(), 400)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM