如何增加tablewidg的行高和列宽

2024-09-29 22:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在单元格中添加图片,但是不能正常显示,你能告诉我如何增加表格小部件的行高和列宽吗。在

以下是我的代码:

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_())

Tags: importselfinitdefsyswidgetclassparent
1条回答
网友
1楼 · 发布于 2024-09-29 22:24:59

当使用QTableWidget中的小部件不是表的内容时,它们被放在表的顶部,因此resizeColumnsToContents()使单元格的大小非常小,因为它没有考虑这些小部件的大小,resizeColumnsToContents()考虑了{}生成的内容。在

另一方面,如果要设置单元格的高度和宽度,则必须使用标题,在下面的示例中,默认大小是使用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)

如果您希望用户不能更改大小,请取消对行的注释。在

相关问题 更多 >

    热门问题