【发布时间】:2021-02-08 19:10:55
【问题描述】:
我正在尝试基于条目 (QLineEdit) 创建按钮 (QPushButtons)。我的想法是,我希望用户能够创建任意数量的按钮,只需在输入框中添加新文本,然后按“添加标签”(见下图)。
虽然我能够做到这一点,但我现在无法检索每个按钮的标签值,因为我使用的过程会删除所有以前的值(我只能检索最后输入的值)。我希望能够在单击每个按钮时打印每个特定的标签值。
我的代码如下:
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setGeometry(100, 100, 1500, 1500)
self.setWindowTitle("My Program")
self.labelButtons = [] # List of all the buttons displaying labels
self.eraseButtons = [] # List of all the buttons displaying "X"
self.Yposition = 50
self.initUI()
def initUI(self):
self.labelEntry = QLineEdit(self)
self.labelEntry.move(50, self.Yposition)
self.labelEntry.resize(300, 40)
self.addLabelButton = QPushButton(self)
self.addLabelButton.setText("Add Label")
self.addLabelButton.move(400, self.Yposition)
self.addLabelButton.resize(300, 40)
self.addLabelButton.clicked.connect(self.addNewLabel)
def addNewLabel(self):
self.Yposition += 50
self.newLabelName = self.labelEntry.text()
self.labelButtons.append(self.createButtonLabel(self.newLabelName))
self.eraseButtons.append(self.eraseButtonLabel())
self.updatelabels()
def createButtonLabel(self, labelname):
self.button = QPushButton(self)
self.button.setText(str(labelname))
self.button.resize(300, 40)
self.button.move(50, self.Yposition)
self.button.clicked.connect(self.printbutton)
return self.button
def eraseButtonLabel(self):
self.buttonErase = QPushButton(self)
self.buttonErase.setText("X")
self.buttonErase.resize(40, 40)
self.buttonErase.move(360, self.Yposition)
self.buttonErase.clicked.connect(self.printbutton)
return self.buttonErase
def updatelabels(self):
for button in self.labelButtons:
button.show()
for button in self.eraseButtons:
button.show()
def printbutton(self):
print(self.button.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
<!-- end snippet -->
【问题讨论】:
-
我不确定,但是当您单击按钮时,
PyQt应该发送event以及widget创建此event的信息(其中button是单击),然后您可以用它来访问widget。我不确定,但也许你需要def printbutton(self, event):? -
您可以添加包含所有导入的代码 - 运行它并测试一些想法会更简单。
-
def printbutton(self): print(self.sender().text())。或者使用QButtonGroup。 -
感谢 self.sender(),它确实允许从每个按钮中检索文本。关于删除按钮你有什么想法吗?同样对于@furas,对不起,我忘了粘贴导入,它们是: from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit import sys
-
下次将导入(以及其他代码、数据和错误消息)放在有问题的地方,不要在评论中 - 它将更具可读性,更多人会看到它。
标签: python for-loop pyqt5 qpushbutton