如何在PyQt中的QTableWidget中的同一单元格中显示图像和文本?

时间:2017-08-26 14:09:31

标签: python qt pyqt pyqt5 qtablewidget

我希望有一个包含2或3列的表,其中的行在PyQt中显示图像和文本(我使用的是python3.5和PyQt 5)。首先我选择了QListWidget,但它仅限于一列。我发现QTableWidget是执行此操作的最佳方式。但是当我在表格中放置一个单元格的图像时,该单元格的文本没有显示在它的底部。如何让单元格在适当的位置显示文本和图像? 这是我的代码:

self.main_table = QTableWidget(self)
self.main_table.setGeometry(QRect(20, 140, 600, 330))
sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.main_table.sizePolicy().hasHeightForWidth())
self.main_table.setSizePolicy(sizePolicy)
self.main_table.setLayoutDirection(Qt.LeftToRight)
self.main_table.setLocale(QLocale(QLocale.Persian, QLocale.Iran))
self.main_table.setInputMethodHints(Qt.ImhNone)
self.main_table.setFrameShape(QFrame.NoFrame)
self.main_table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.main_table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.main_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.main_table.setTabKeyNavigation(False)
self.main_table.setShowGrid(False)
self.main_table.setCornerButtonEnabled(False)
self.main_table.setIconSize(QSize(210,150))

self.main_table.setRowCount(2)
self.main_table.setColumnCount(2)


self.main_table.setObjectName("main_table")
self.main_table.horizontalHeader().setVisible(False)
self.main_table.horizontalHeader().setHighlightSections(False)
self.main_table.verticalHeader().setVisible(False)
self.main_table.verticalHeader().setHighlightSections(False)
self.main_table.horizontalHeader().setDefaultSectionSize(250)
self.main_table.verticalHeader().setDefaultSectionSize(250)

self.item = QTableWidgetItem(QIcon('content/img/food.png'),'Food')
self.main_table.setItem(0 , 0, self.item)

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用创建自定义小部件,我们可以根据需要找到元素,下面的代码实现了顶部的图标和下面的文本。

class CustomWidget(QWidget):
    def __init__(self, text, img, parent=None):
        QWidget.__init__(self, parent)

        self._text = text
        self._img = img

        self.setLayout(QVBoxLayout())
        self.lbPixmap = QLabel(self)
        self.lbText = QLabel(self)
        self.lbText.setAlignment(Qt.AlignCenter)

        self.layout().addWidget(self.lbPixmap)
        self.layout().addWidget(self.lbText)

        self.initUi()

    def initUi(self):
        self.lbPixmap.setPixmap(QPixmap(self._img).scaled(self.lbPixmap.size(),Qt.KeepAspectRatio))
        self.lbText.setText(self._text)


    @pyqtProperty(str)
    def img(self):
        return self._img

    @img.setter
    def total(self, value):
        if self._img == value:
            return
        self._img = value
        self.initUi()

    @pyqtProperty(str)
    def text(self):
        return self._text

    @text.setter
    def text(self, value):
        if self._text == value:
            return
        self._text = value
        self.initUi()

然后通过setCellWidget()函数添加小部件以添加它们,并使用resizeColumnsToContents()resizeRowsToContents()缩放每个单元格的空间,如下所示:

class TableWidget(QTableWidget):
    def __init__(self, parent=None):
        QTableWidget.__init__(self, parent)
        self.setColumnCount(5)
        self.setRowCount(5)
        for i in range(self.columnCount()):
            for j in range(self.rowCount()):
                lb = CustomWidget(str(i)+str(j), "/path/of/image")
                self.setCellWidget(i, j, lb)

        self.resizeColumnsToContents()
        self.resizeRowsToContents()
        self.cellClicked.connect(self.onCellClicked)

    @pyqtSlot(int, int)
    def onCellClicked(self, row, column):
        w = self.cellWidget(row, column)
        print(w.text, w.img)


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    tw = TableWidget()

    tw.show()
    sys.exit(app.exec_())

enter image description here