[英]Change text when button is clicked
我想在單擊文本時將按鈕上的文本( Start optimization
)更改為( Cancel optimization
)。 到目前為止我得到了:
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
layout = QGridLayout()
layout.addLayout(self.optimize_button(), 1, 3, 1, 1)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
# method for widgets
def optimize_button(self):
hbox = QHBoxLayout()
button = QPushButton("", self)
button.setText("Start optimization")
button.setGeometry(200, 150, 100, 30)
button.clicked.connect(self.clickme)
#self.push.clicked.connect(self.clickme)
hbox.addWidget(button)
self.show()
return hbox
def clickme(self):
print("pressed")
self.button.setText("Cancel optimization")
我試圖利用https://www.geeksforgeeks.org/pyqt5-how-to-change-the-text-of-existing-push-button/但它不起作用。 我想問題出在某個地方,點擊按鈕正在調用clickme()
,它對那個按鈕一無所知。 但我不知道如何相應地參考。
編輯:
def clickme(self):
print("pressed")
self.button = QPushButton("", self)
self.button.setText("Cancel optimization")
不管用?
一個解決方案是:
因此,您的簡化示例將變為:
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
hbox = QHBoxLayout()
self.button = QPushButton("", self) // (1) store the button as a class member
button.setText("Start optimization")
button.clicked.connect(self.clickme)
hbox.addWidget(button)
widget = QWidget()
widget.setLayout(hbox)
self.setCentralWidget(widget)
self.show()
def clickme(self):
print("pressed")
self.button.setText("Cancel optimization") // (2) self.button is the button stored in (1)
QObject::sender
如評論中所述,使用QObject::sender
可能是在clickme
中獲取單擊按鈕的替代方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.