从PyQt5中的QTableWidget删除单元格填充

问题描述

我正在尝试将QTableWidget与PyQt5和QtDesigner结合使用,以在GUI的网格中显示图像。 (我正在模拟一个LED面板显示器。)我希望每个图像都可以独立于其他图像进行更改,并在空间上与网格中的相邻图像相切。我遇到的问题是我找不到消除单元格填充的方法,因此我无法使图像看起来像形成连续的马赛克。有谁知道有没有办法做到这一点?

编辑:这是更多信息:

class Home_Win(QMainWindow):
    def __init__(self):
        # Show GUI------------------------
        QMainWindow.__init__(self)
        self.ui = loadUi("bugpanel.ui",self)
        blueLED = QTableWidgetItem(QIcon("img/blueLED.jpg"),'',0)
        rows,cols = 16,32
        for row in range(rows):
            for col in range(cols):
                self.tableWidget_2.setItem(0,QTableWidgetItem(QIcon("img/greenLED.jpg"),0))
        self.tableWidget_2.setItem(0,1,blueLED)

我想要什么:

simulated LED panel picture

我得到的是

enter image description here

解决方法

您必须通过委托来实现自定义绘制,另外最好设置一个默认大小来覆盖委托的sizeHint()方法,并调用resizeRowsToContents()和resizeColumnsToContents()方法:

import random

from PyQt5 import QtCore,QtGui,QtWidgets


class IconDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self,painter,option,index):
        icon = index.data(QtCore.Qt.DecorationRole)
        mode = QtGui.QIcon.Normal
        if not (option.state & QtWidgets.QStyle.State_Enabled):
            mode = QtGui.QIcon.Disabled
        elif option.state & QtWidgets.QStyle.State_Selected:
            mode = QtGui.QIcon.Selected
        state = (
            QtGui.QIcon.On
            if option.state & QtWidgets.QStyle.State_Open
            else QtGui.QIcon.Off
        )
        pixmap = icon.pixmap(option.rect.size(),mode,state)
        painter.drawPixmap(option.rect,pixmap)

    def sizeHint(self,index):
        return QtCore.QSize(60,60)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self,parent=None):
        super().__init__(parent)

        table = QtWidgets.QTableWidget(10,10)
        delegate = IconDelegate(table)
        table.setItemDelegate(delegate)

        self.setCentralWidget(table)

        for i in range(table.rowCount()):
            for j in range(table.columnCount()):

                # create icon
                pixmap = QtGui.QPixmap(100,100)
                color = QtGui.QColor(*random.sample(range(255),3))
                pixmap.fill(color)
                icon = QtGui.QIcon(pixmap)

                it = QtWidgets.QTableWidgetItem()
                it.setIcon(icon)
                table.setItem(i,j,it)

        table.resizeRowsToContents()
        table.resizeColumnsToContents()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

enter image description here