使用PyQt和QTableWidget在horizo​​ntalHeaderItem中设置图像

时间:2011-04-06 23:23:37

标签: qt pyqt qtablewidget qtablewidgetitem

我尝试对QTableWidgetItem进行子类化,然后使用新的子类类设置我的horizo​​ntalHeaderItem。例如:

class ImageWidget(QtGui.QTableWidgetItem):

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 showTable(QtGui.QDialog):

def __init__(self, parent=None):
    tableWidget = QtGui.QTableWidget(10, 2)
    imagePath = "C:/Documents and Settings/pwr37669/workspace/Pro_GUI_Py/images/led_green.gif"
    item = ImageWidget(imagePath, QtGui.QTableWidgetItem())
    tableWidget.setHorizontalHeaderItem(0, item)

    tableWidget.show() 

我知道代码不起作用,但是,我正试图让这样的东西起作用。

我还需要更改单击单元格或标题的结果。

非常感谢任何帮助。 谢谢, 斯蒂芬

2 个答案:

答案 0 :(得分:3)

以下似乎可以解决问题:

class ImgWidget1(QtGui.QLabel):

    def __init__(self,imagePath, parent=None):
        super(ImgWidget1, self).__init__(parent)

        pic = QtGui.QPixmap(imagePath)
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setPixmap(pic)

然后当我想添加图像时,我这样做了:

self.tableWidget.setCellWidget(rows, cells, ui_polling.ImgWidget1(imagePath))

希望这可以帮助那些人。

答案 1 :(得分:1)

请检查以下示例是否适合您:

import sys
from PyQt4 import QtGui, QtCore

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        tableWidget = QtGui.QTableWidget()
        tableWidget.setRowCount(3)
        tableWidget.setColumnCount(2)

        for column in range(0, 2):
            for row in range(0, 3):
                print row, column
                item = QtGui.QTableWidgetItem("new item")
                tableWidget.setItem(row, column, item)

        headerItem = QtGui.QTableWidgetItem("Header Test")
        headerItem.setIcon(QtGui.QIcon(QtGui.QPixmap("your_image.png")))
        headerItem.setTextAlignment(QtCore.Qt.AlignVCenter);

        tableWidget.setHorizontalHeaderItem(0, headerItem)

        tableWidget.itemClicked.connect(self.on_tableWidget_itemClicked)
        tableWidget.connect(tableWidget.horizontalHeader(), QtCore.SIGNAL('sectionClicked(int)'), self.on_headersection_clicked)

        self.setCentralWidget(tableWidget)

    def on_tableWidget_itemClicked(self, item):
        print "item clicked " + item.text()

    def on_headersection_clicked(self, item):
        print "header section clicked " + str(item) 

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

希望这有帮助,尊重