【发布时间】:2020-05-18 19:20:26
【问题描述】:
我正在尝试创建一个延伸到窗口宽度和高度的网格小部件。网格的大小(当前为 14x49)可能会发生变化,但我希望小部件的整体大小保持不变。
代码:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLayout,
QGridLayout, QSizePolicy, QGraphicsScene, QGraphicsView
from PyQt5.QtCore import QCoreApplication, QSize, Qt, QRectF, QPointF, QSizeF
from PyQt5.QtGui import QColor, QPen, QBrush, qRgb
class Map(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initUI()
def initUI(self):
self.setMinimumSize(500, 500) # min-size of the widget
self.columns = 14 # num of columns in grid
self.rows = 49 # num of rows in grid
def resizeEvent(self, event):
# compute the square size based on the aspect ratio, assuming that the
reference = self.width() * self.rows / self.columns
if reference > self.height():
# the window is larger than the aspect ratio
# use the height as a reference (minus 1 pixel)
self.squareSize = (self.height() - 1) / self.rows
else:
# the opposite
self.squareSize = (self.width() - 1) / self.columns
def paintEvent(self, event):
grid = QGridLayout()
self.sceneWithPen(grid)
self.setLayout(grid)
# creates the grid of squares
def sceneWithPen(self, grid):
scene = QGraphicsScene()
w = QGraphicsView()
w.setScene(scene)
side = self.squareSize
brush = QBrush(QColor(qRgb(255, 255, 255))) # background color of square
pen = QPen(Qt.black) # border color of square
for i in range(self.rows):
for j in range(self.columns):
r = QRectF(QPointF(
i*side, j*side), QSizeF(side, side)) # each square
scene.addRect(r, pen, brush)
grid.addWidget(w)
if __name__ == "__main__":
app = QApplication(sys.argv)
view = Map()
view.show()
sys.exit(app.exec_())
我希望小部件看起来像什么:
【问题讨论】: