如何在PyQt的小区中心的形象?

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

我想展示里面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_())
python pyqt
1个回答
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)
        ...

结果:

result

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