python - 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_())
预期输出:
解决方案
推荐阅读
- java - 是否可以分离 javafx ui 文件?
- javascript - 来自画布的简单形式的 raect-admin 图像
- sql - Laravel 规范搜索
- html - 使活动链接保持粗体,不仅在我单击它时变为粗体
- d - 为什么 D 中的固定长度字符数组允许直接字符串赋值?
- javascript - 我已经制作了一个登录表单,但我无法使用 Javascript 代码进行验证
- android - 为什么我的 AutoCompleteTextView 不起作用?
- javascript - Javascript - 遗漏一个值?
- c - 两种不同的交换功能有什么区别?
- python - 在python3中打印本体类时出现问题