首页 > 解决方案 > PyQt5:如何使用 QGraphicsScene 制作网格?

问题描述

问题描述:

我正在尝试创建一个如下图所示的网格。我想通过使用 PyQt5 中的 QGraphicsScene 类来做到这一点。当我运行下面提供的代码时,会打开一个窗口,但看不到网格。有人可以帮我弄清楚如何让网格出现吗?

最小可重现代码:

import sys
from PyQt5.QtGui import QIcon, QPainter, QColor, QPen
from PyQt5.QtCore import QCoreApplication, QRect, QSize, Qt, QRectF
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QGraphicsScene, QGraphicsView

class Map(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.initUI()

    def initUI(self):
        self.setMinimumSize(800, 600)
        self.columns = 10
        self.rows = 10

    def setColumnSize(self, columnSize):
        self.columns = columnSize

    def setRowsSize(self, rowSize):
        self.rows = rowSize

    def resizeEvent(self, event):
        # compute the square size based on the aspect ratio, assuming that the
        # column and row numbers are fixed
        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):
        qg = QGraphicsScene(self)
        width = self.squareSize * self.columns
        height = self.squareSize * self.rows
        # center the grid
        left = (self.width() - width) / 2
        top = (self.height() - height) / 2
        y = top
        # we need to add 1 to draw the topmost right/bottom lines too
        for row in range(self.rows + 1):
            qg.addLine(left, y, left + width, y)
            y += self.squareSize
        x = left
        for column in range(self.columns + 1):
            qg.addLine(x, top, x, top + height)
            x += self.squareSize

if __name__ == "__main__":
    app = QApplication(sys.argv)
    view = Map()
    view.show()
    sys.exit(app.exec_())

预期输出:

在此处输入图像描述

标签: pythonpyqt5

解决方案


推荐阅读