我有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脚本编写器noob。
答案 0 :(得分:0)
您应该在项目创建后设置这些标志:
block.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
block.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)