如何增加qtablewidget的行高和列宽

问题描述 投票:1回答:1

我想将图像添加到单元格,但它无法正常显示,你能告诉我如何增加表格小部件的行高和列宽。

下面给出以下是我的代码:

from PyQt4 import QtGui
import sys

imagePath = "pr.png"

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.horizontalHeader().setStretchLastSection(True)
        tableWidget.resizeColumnsToContents()
        # tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # tableWidget.setFixedWidth(tableWidget.columnWidth(0) + tableWidget.columnWidth(1))
        tableWidget.resize(400,600)
        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_())
python python-3.x pyqt pyqt4 qtablewidget
1个回答
1
投票

当在QTableWidget中使用小部件并不是表格的内容时,它们被置于其上面,因此resizeColumnsToContents()使单元格的大小非常小,因为它没有考虑这些小部件的大小,resizeColumnsToContents()考虑到QTableWidgetItem生成的内容。

另一方面,如果要设置单元格的高度和宽度,则必须使用标题,在以下示例中,使用setDefaultSectionSize()设置默认大小:

class Widget(QtGui.QWidget):
    def __init__(self):
        super(Widget, self).__init__()
        tableWidget = QtGui.QTableWidget(10, 2)

        vh = tableWidget.verticalHeader()
        vh.setDefaultSectionSize(100)
        # vh.setResizeMode(QtGui.QHeaderView.Fixed)

        hh = tableWidget.horizontalHeader()
        hh.setDefaultSectionSize(100)
        # hh.setResizeMode(QtGui.QHeaderView.Fixed)

        tableWidget.setCellWidget(0, 1, ImgWidget1())
        tableWidget.setCellWidget(1, 1, ImgWidget2())

        lay = QtGui.QVBoxLayout(self)
        lay.addWidget(tableWidget)

如果您希望用户无法改变大小,则取消注释行。

© www.soinside.com 2019 - 2024. All rights reserved.