在PYQT5中单击新按钮时,如何取消所选按钮(QPUSHBUTTON)的操作?
`类MainWindow(Qwidget): def init (self): super()。 init ()
self.setWindowTitle("Window")
self.setGeometry(600, 100, 600, 400)
self.Function()
def Function(self):
xpos = 10
for i in range(5):
button = QPushButton("".format(i+1), self)
button.setGeometry(xpos, 150, 50, 50 )
xpos = xpos + 50
button.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")
button.clicked.connect(lambda ch, i=i+1: self.function(i))
button.clicked.connect(lambda ch, i=button : self.color(i))
def function(self, i):
print(i)
def color(self, i):
i.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")`i am new to this sort of programming, and
我试图创建并排对齐的一行按钮(以输入为输入的按钮数)。曾经单击的按钮(qpushbutton)应采用颜色,当单击另一个按钮时,应取消以前的操作,并且必须对新选择的按钮进行颜色。
我能够使用“ btn.clicked.connect(...)”方法使所选按钮获得颜色。但是,当单击其他按钮时,先前的按钮将保持颜色而不会默认。 我必须如何正确执行?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以做到的一种方法是使用self.sender()方法。
这将告诉您单击哪个按钮。然后,您可以循环浏览其他按钮,然后将其样式表更改为默认颜色。
/I.sstatic.net/7bgms.png“ alt =”在此处输入图像说明”>
One way you can do it is by using the self.sender() method.
This will tell you which button was clicked. Then you can loop through the other buttons and change their style sheet to some default color.
您声明
按钮
的方式很难稍后引用。我可以考虑以下两种方式:放入列表中
的按钮
将
您 。如果要保存最后一个按钮,则只需要修改最后一个按钮和当前按钮:
The way you've declared
button
it's hard to refer to it later on. I can think of two ways around this:put your buttons in a list
put your buttons in a QButtonGroup
a little more efficient...
Both cases as I've coded them are a little kludgy since they go though ALL of the buttons every time you click ONE button. If you were to save the last button pressed, then you would only have to modify the last button and the current button:
以上代码可能对您有用。对于您要问的其他问题,请不要忘记添加示例代码:
The above code probably will work for you. For the further questions you are going to ask, do not forget to add your sample code:
https://stackoverflow.com/help/minimal-reproducible-example