我想在PyQt5的QTableWidget
的单元格内显示一些图像。问题是我不知道如何将它们带到单元格的中心,而不是在左上角显示它们。
from PyQt5 import QtWidgets, QtGui
import os
import sys
class Example(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self._main = QtWidgets.QWidget()
self.setCentralWidget(self._main)
self.dashboard_table = QtWidgets.QTableWidget(1,1)
self.dashboard_table.setCellWidget(0, 0, ImgWidget(os.getcwd() + '/img/green.png'))
header = self.dashboard_table.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
layout = QtWidgets.QVBoxLayout(self._main)
layout.addWidget(self.dashboard_table)
self.showMaximized()
class ImgWidget(QtWidgets.QLabel):
def __init__(self, path, parent=None):
super(ImgWidget, self).__init__(parent)
pic = QtGui.QPixmap(path)
pic = pic.scaledToWidth(32)
self.setPixmap(pic)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
ex = Example()
ex.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
将您的ImgWidget
添加到布局中并设置“拉伸”:
class Example(QtWidgets.QMainWindow):
def __init__(self, parent=None):
...
self.dashboard_table = QtWidgets.QTableWidget(1,1)
frameWidget = QtWidgets.QWidget()
layout = QtWidgets.QGridLayout()
layout.setContentsMargins(0,0,0,0)
imgw = ImgWidget(os.getcwd() + '/img/green.png')
layout.addWidget(imgw,0,1) #add the widget in the second colum
layout.setColumnStretch(0,1) #set stretch of first
layout.setColumnStretch(2,1) #and third column
frameWidget.setLayout(layout)
self.dashboard_table.setCellWidget(0, 0, frameWidget)
...
结果: