为什么我的自定义QGraphicsItem没有显示在指定的坐标上?

2024-09-29 21:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过编写一个围棋游戏实现来自学python。 我想为这些石头做一个定制的QGraphics项目。你知道吗

此时,它只能画一个以给定坐标为中心的圆(测试)。 但由于某种原因,这个项目出现在我的场景的不同坐标上。 我的意思是,我已经画了一个网格线的董事会到现场,并呼吁我的石头项目与相同的坐标,我使用的网格,但它没有出现在预期的网格点。你知道吗

我的项目代码:

from PyQt5.QtWidgets import QGraphicsItem
from PyQt5.QtCore import QRectF

class Stone(QGraphicsItem):
    """
    A Go stone QGraphicsItem
    x, y :: center Coords of Stone
    rad :: radius
    color:: the stone type
        0, self.empty :: empty
        1, self.black :: black
        2, self.white :: white
    """
    empty = 0
    black = 1
    white = 2

    def __init__(self, x, y, rad, color):
        super().__init__()

        self.x = x
        self.y = y
        self.rad = rad
        self.color = color
        self.setPos(x, y)

    def boundingRect(self):
        rect = QRectF(-self.rad, -self.rad,
                      self.rad, self.rad)
        return rect

    def paint(self, painter, *args, **kwargs):
        painter.drawEllipse(self.boundingRect())

有关更多上下文,可以在https://github.com/drseilzug/GoGote/blob/master/GoGote/BoardGUI.py找到整个代码

我对PyQt5还是相当陌生的,如果有一个解释能帮助我理解问题所在的解决方案,我将不胜感激。你知道吗

谢谢你, Seilzug博士


Tags: 项目代码fromimportself网格defpyqt5
1条回答
网友
1楼 · 发布于 2024-09-29 21:25:12

我发现了我的错误。你知道吗

问题是,我误解了QRectF对象参数的解释方式。我以为这4个浮点数是左上角和右下角的坐标,而实际上第一个浮点数确实是左上角,但第二个浮点数给出了矩形的尺寸。你知道吗

通过将boundingRect更改为

def boundingRect(self):
    rect = QRectF(-self.rad, -self.rad,
                  2*self.rad, 2*self.rad)
    return rect

相关问题 更多 >

    热门问题