无法使用鼠标cli移动QGraphicsRectItem

2024-05-09 02:10:29 发布

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

我将qgraphicsrecitem()定义如下

def create_blocks(self):
    """
    Creates block rectangles and adds them to scene.
    """
    for i in range(self.nrows):
        line_block = []
        for j in range(self.ncols):
            block = QGraphicsRectItem(0, 0, 100, 100)
            block.setPos(j * 100, i * 100)
            self.scene.addItem(block)
            line_block.append(block)
        self.block_array.append(line_block)

这些rect项按以下方式填充:

def fillData(self):
    """
    Fill puzzle blocks with numbers and remove SPACER block.
    Fills puzzle block with color - zigzag
    """
    color1 = Qt.lightGray
    color2 = Qt.gray
    last_color = color1
    color_table = {}

    # generate dict with color for each number (1-lgray, 2-gray, 3-lgray, etc.)
    keys = xrange(1, 16)
    for key in keys:
        color_table[key] = last_color
        last_color = color1 if last_color == color2 else color2

    for j in range(self.ncols):
        for i in range(self.nrows):
            block = self.block_array[i][j]
            blockBoundRect = block.boundingRect()
            block.mousePressEvent(Qt.LeftButton)
            num = self.init_data[i][j]
            if num == self.SPACER:
                self.scene.removeItem(block)
                continue
            else:
                text = str(num)
                block.setBrush(QColor(color_table[num]))

            textItem = QGraphicsSimpleTextItem(text, block)
            font = textItem.font()
            font.setPixelSize(50)
            textItem.setFont(font)
            textItemBoundRect = textItem.boundingRect()
            new_x = blockBoundRect.width() / 2.0 - textItemBoundRect.width() / 2.0
            new_y = blockBoundRect.height() / 2.0 - textItemBoundRect.height() / 2.0
            textItem.setPos(new_x, new_y)

block.mousePressEvent(Qt.LeftButton)

有了这一行,我试图启用点击矩形,我现在还不能这样做。我需要帮助有人告诉我在哪里写的逻辑,如果按钮点击旁边的空白位置,移动矩形

我正在尝试用python制作一个15个益智游戏,我已经将后端代码连接到GUI,解算器部分工作正常。我以前没有使用QT的经验,我基本上是一个python脚本作者noob


Tags: inselfnewforwithlinerangescene