10

私はPythonに非常に慣れておらず、PyQtにも慣れていません。テーブルを作成できましたが、特定のセルに画像を追加したいと思います。QTableWidgetクラス、または場合によってはQTableWidgetItemクラスをサブクラス化し、QPaintEventを再実装する必要があることを読みました。QPaintEventの再実装に何が入るかの例を誰かが持っているなら、私はそれを本当に感謝します。

ありがとう、スティーブン

4

2 に答える 2

16
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を要求したので、それを行う2つの方法。

クレジット: http://www.mail-archive.com/pyqt@riverbankcomputing.com/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_())
于 2011-04-05T18:00:35.487 に答える