无法通过鼠标单击移动 QGraphicsRectItem
Posted
技术标签:
【中文标题】无法通过鼠标单击移动 QGraphicsRectItem【英文标题】:Unable to move a QGraphicsRectItem with mouse click 【发布时间】:2017-07-02 10:58:11 【问题描述】:我的 QGraphicsRectItem() 定义如下
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)
这些矩形项的填写方式如下:
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 脚本编写者。
【问题讨论】:
【参考方案1】:您应该在项目创建后设置这些标志:
block.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
block.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
【讨论】:
以上是关于无法通过鼠标单击移动 QGraphicsRectItem的主要内容,如果未能解决你的问题,请参考以下文章