向PyQt中的QTableWidget添加图像

问题描述 投票:6回答:2

我是Python的新手,甚至是PyQt的新手。我设法创建了一个表,但是想在某些单元格中添加图像。我已经读过我需要继承QTableWidget类,或者可能是QTableWidgetItem类,并重新实现QPaintEvent。如果有人举了重新实现QPaintEvent的例子,我将不胜感激。

谢谢,斯蒂芬

python pyqt qtablewidget qtablewidgetitem
2个回答
13
投票
from PyQt4 import QtGui
import sys

imagePath = "enter the path to your image here"

class ImgWidget1(QtGui.QLabel):

    def __init__(self, parent=None):
        super(ImgWidget1, self).__init__(parent)
        pic = QtGui.QPixmap(imagePath)
        self.setPixmap(pic)

class ImgWidget2(QtGui.QWidget):

    def __init__(self, parent=None):
        super(ImgWidget2, self).__init__(parent)
        self.pic = QtGui.QPixmap(imagePath)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(0, 0, self.pic)


class Widget(QtGui.QWidget):

    def __init__(self):
        super(Widget, self).__init__()
        tableWidget = QtGui.QTableWidget(10, 2, self)
        tableWidget.setCellWidget(0, 1, ImgWidget1(self))
        tableWidget.setCellWidget(1, 1, ImgWidget2(self))

if __name__ == "__main__":
    app = QtGui.QApplication([])
    wnd = Widget()
    wnd.show()
    sys.exit(app.exec_())

两种方法,因为您要求了painEvent。

信用:http://www.mail-archive.com/[email protected]/msg01259.html

希望这会有所帮助。

编辑:使用QTableWidget子类添加了请求的解决方案。

from PyQt4 import QtGui
import sys

class ImageWidget(QtGui.QWidget):

    def __init__(self, imagePath, parent):
        super(ImageWidget, self).__init__(parent)
        self.picture = QtGui.QPixmap(imagePath)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(0, 0, self.picture)


class TableWidget(QtGui.QTableWidget):

    def setImage(self, row, col, imagePath):
        image = ImageWidget(imagePath, self)
        self.setCellWidget(row, col, image)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    tableWidget = TableWidget(10, 2)
    tableWidget.setImage(0, 1, "<your image path here>")
    tableWidget.show()
    sys.exit(app.exec_())

0
投票

我发现这个解决方案对我的初学者来说很友善:

from PyQt5 import QtCore, QtGui, QtWidgets
import sys

class KindForMind(object):
    def THINK(self, PLEASE):
        self.table = QtWidgets.QTableWidget()
        pic = QtGui.QPixmap("your_image.jpg")
        self.label = QtWidgets.QLabel(PLEASE)
        self.label.setPixmap(pic)
        self.table.setCellWidget(0,0, self.label)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    PLEASE = QtWidgets.QWidget()
    ui = KindForMind()
    ui.THINK(PLEASE)
    PLEASE.show()
    sys.exit(app.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.