我正在尝试制作一个游戏,在单击按钮时,可以在侧面移动一行按钮。
到目前为止,我在布局中使用了担架,可以将担架设置为所需的不同状态,但不能动态设置。当我按下按钮时,数据会更新,但是使用update()或repaint()根本不起作用(我可能会错误地使用它们)。
decal = [0,0,0,0] #values between -3 and +3, one for each row
class grid(QWidget):
"""
creates the grid layout by aligning a set of rows
"""
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QVBoxLayout()
layout.addStretch()
layout.setSpacing(0)
for i in range(4):
layout.addItem(row(i))
layout.addStretch()
self.setLayout(layout)
class row(QHBoxLayout):
def __init__(self, ligne):
super().__init__()
self.ligne = ligne
self.initUI()
def initUI(self):
# ajout des widgets et stretch
self.addWidget(rangmoins(self.ligne))
self.addStretch(3 + decal[self.ligne])
for i in range(4):
self.addWidget(gridbutton(self.ligne, i))
self.addStretch(3 - decal[self.ligne]) # I modify the decal value to move the row and the size of the stretch
self.addWidget(rangplus(self.ligne))
self.setSpacing(0)
class rangplus(QPushButton):
"""
modifies the values of decal to change the stretchitems size
"""
def __init__(self, ligne):
super().__init__()
self.side = 52
self.clicked.connect(self.on_click)
self.ligne = ligne
self.initUI()
def initUI(self):
self.setFixedSize(self.side, self.side)
self.setText(">")
def on_click(self):
global joueur
if decal[self.ligne] != 3:
joueur = joueur % 2 + 1
decal[self.ligne] += 1
window.repaint() # need to update the window so it displays the change
else:
print("coup impossible")
很难提供适合您的代码的答案,因为并非所有变量都在您提供的代码段中定义。但是,这是使用QGridLayout实现此目的的一般方法。您要做的是删除该行中的每个按钮,将其替换为QSpacerItem,然后将该按钮插入另一侧的新列中。尝试运行此示例,看看是否可以将其适应您的代码:
class Template(QWidget):
def __init__(self):
super().__init__()
self.grid = QGridLayout(self)
self.grid.setHorizontalSpacing(0)
for row in range(4):
for col in range(4):
self.grid.addWidget(QPushButton(str(row)), row, col)
for i in range(4):
btn = QPushButton('>')
btn.clicked.connect(self.move_buttons)
self.grid.addWidget(btn, i, 4)
def move_buttons(self):
row = self.grid.getItemPosition(self.grid.indexOf(self.sender()))[0]
for col in range(4):
btn = self.grid.itemAtPosition(row, col).widget()
self.grid.removeWidget(btn)
self.grid.addWidget(btn, row, col + 5)
self.grid.addItem(QSpacerItem(btn.width(), btn.height(), QSizePolicy.Maximum, QSizePolicy.Maximum), row, col)