在PYQT5中单击新按钮时,如何取消所选按钮(QPUSHBUTTON)的操作?

发布于 2025-02-08 04:18:37 字数 1044 浏览 1 评论 0 原文

`类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(...)”方法使所选按钮获得颜色。但是,当单击其他按钮时,先前的按钮将保持颜色而不会默认。 我必须如何正确执行?

`class 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 

i am trying to create a row of buttons (number of buttons are given as input) that are aligned side by side. A button (QPushButton) that is once clicked should take on a color, and when an other button is clicked, the previous action should be canceled and the new selected button must be colored.

I was able to use the "btn.clicked.connect(...)" method to make the selected button get colored. But when the other buttons are clicked the previous ones keep the color without going into default.
How do i have to do it correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

倦话 2025-02-15 04:18:37

您可以做到的一种方法是使用self.sender()方法。
这将告诉您单击哪个按钮。然后,您可以循环浏览其他按钮,然后将其样式表更改为默认颜色。

class MainWindow(QtWidgets.QMainWindow, ui_MainWindow):
    def __init__(self):
   
        QtWidgets.QMainWindow.__init__(self)
        ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.pushButton_1.clicked.connect(self.color_buttons)
        self.pushButton_2.clicked.connect(self.color_buttons)
        self.pushButton_3.clicked.connect(self.color_buttons)
    
        self.button_list = [self.pushButton_1, self.pushButton_2, self.pushButton_3]

        self.button_default_css  = "background-color: rgb(225, 225, 225);"
        self.button_selected_css = "background-color: rgb(102, 176, 54);"
    

    def color_buttons(self):
        print(f"\nButton Pressed : {self.sender().objectName()}")
        for button in self.button_list:
            if button == self.sender():
                button.setStyleSheet(self.button_selected_css)
            else:
                button.setStyleSheet(self.button_default_css) 

​/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.

class MainWindow(QtWidgets.QMainWindow, ui_MainWindow):
    def __init__(self):
   
        QtWidgets.QMainWindow.__init__(self)
        ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.pushButton_1.clicked.connect(self.color_buttons)
        self.pushButton_2.clicked.connect(self.color_buttons)
        self.pushButton_3.clicked.connect(self.color_buttons)
    
        self.button_list = [self.pushButton_1, self.pushButton_2, self.pushButton_3]

        self.button_default_css  = "background-color: rgb(225, 225, 225);"
        self.button_selected_css = "background-color: rgb(102, 176, 54);"
    

    def color_buttons(self):
        print(f"\nButton Pressed : {self.sender().objectName()}")
        for button in self.button_list:
            if button == self.sender():
                button.setStyleSheet(self.button_selected_css)
            else:
                button.setStyleSheet(self.button_default_css) 

enter image description here

enter image description here

enter image description here

小ぇ时光︴ 2025-02-15 04:18:37

您声明按钮的方式很难稍后引用。我可以考虑以下两种方式:

  1. 列表中
  2. 将您的按钮放入 qbuttongroup

放入列表中

class MainWindow(QWidget): 

    def __init__(self): 
        super().__init__()
        self.setWindowTitle("Window")
        self.setGeometry(600, 100, 600, 400)
        self.Function()

    def Function(self):
        xpos = 10

    self.button_list = []

    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")
        self.button_list.append(button)
        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):
        bnum = int(i.text())
        for idx, button in enumerate(self.button_list):
            if idx+1 == bnum:
                button.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")
            else:
                button.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")

的按钮

class MainWindow(QWidget): 

    def __init__(self): 
        super().__init__()
        self.setWindowTitle("Window")
        self.setGeometry(600, 100, 600, 400)
        self.Function()

    def Function(self):
        xpos = 10

    self.button_group = QButtonGroup()

    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")
        self.button_group.addButton(button, id=i+1)
        self.button_group.idClicked.connect(self.color)
        self.button_group.idClicked.connect(self.function)
     
    # arguments have changed bid is the button id assigned in addButton
    def function(self, bid):
        print(self.button_group.button(bid))

    def color(self, bid):
        bcount = len(self.button_group.buttons())
        for i in range(bcount)
            if i+1 == bid:
                button.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")
            else:
                button.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")

您 。如果要保存最后一个按钮,则只需要修改最后一个按钮和当前按钮:

btn = self.button_group.button(self.last_bid)
btn.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")

btn = self.button_group.button(bid)
btn.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")

self.last_bid = bid

The way you've declared button it's hard to refer to it later on. I can think of two ways around this:

  1. put your buttons in a list
  2. put your buttons in a QButtonGroup

put your buttons in a list

class MainWindow(QWidget): 

    def __init__(self): 
        super().__init__()
        self.setWindowTitle("Window")
        self.setGeometry(600, 100, 600, 400)
        self.Function()

    def Function(self):
        xpos = 10

    self.button_list = []

    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")
        self.button_list.append(button)
        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):
        bnum = int(i.text())
        for idx, button in enumerate(self.button_list):
            if idx+1 == bnum:
                button.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")
            else:
                button.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")

put your buttons in a QButtonGroup

class MainWindow(QWidget): 

    def __init__(self): 
        super().__init__()
        self.setWindowTitle("Window")
        self.setGeometry(600, 100, 600, 400)
        self.Function()

    def Function(self):
        xpos = 10

    self.button_group = QButtonGroup()

    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")
        self.button_group.addButton(button, id=i+1)
        self.button_group.idClicked.connect(self.color)
        self.button_group.idClicked.connect(self.function)
     
    # arguments have changed bid is the button id assigned in addButton
    def function(self, bid):
        print(self.button_group.button(bid))

    def color(self, bid):
        bcount = len(self.button_group.buttons())
        for i in range(bcount)
            if i+1 == bid:
                button.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")
            else:
                button.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")

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:

btn = self.button_group.button(self.last_bid)
btn.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")

btn = self.button_group.button(bid)
btn.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")

self.last_bid = bid
何其悲哀 2025-02-15 04:18:37
btn.clicked.disconnect() 

以上代码可能对您有用。对于您要问的其他问题,请不要忘记添加示例代码:

btn.clicked.disconnect() 

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文