Python 如何增加tablewidget的行高和列宽
我想将图像添加到单元格中,但无法正确显示,请告诉我如何增加表格小部件的行高和列宽 下面是我的代码:Python 如何增加tablewidget的行高和列宽,python,python-3.x,pyqt,pyqt4,qtablewidget,Python,Python 3.x,Pyqt,Pyqt4,Qtablewidget,我想将图像添加到单元格中,但无法正确显示,请告诉我如何增加表格小部件的行高和列宽 下面是我的代码: 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.QPi
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_())
当在
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)