【问题标题】:How to read QLineEdit and QCheckBox value when clicked on a PushButton in PyQt5? [duplicate]单击 PyQt5 中的 PushButton 时如何读取 QLineEdit 和 QCheckBox 值? [复制]
【发布时间】:2020-06-05 22:10:06
【问题描述】:

我正在尝试使用下面的代码,但执行时显示“Python 已停止工作”并重新启动 shell。基本上我试图在单击按钮时从 QLineEdit (用户输入)值中读取文本,但它失败了。

class Display(QWidget):    
    def __init__(self):
        super().__init__()
        self.initUI()


    def initUI(self):
        search_dir_label = QLabel('Directory to Search')
        search_dir_te = QLineEdit()
        search_dir_layout = QHBoxLayout(self)
        search_dir_layout.addWidget(search_dir_label)
        search_dir_layout.addWidget(search_dir_te)
        vert_layout1.addLayout(search_dir_layout)

        search_button = QPushButton('Search')
        search_button.clicked.connect(self.sendval)   
        cancel_button = QPushButton('Cancel')
        search_cancel_layout = QHBoxLayout(self)
        search_cancel_layout.addWidget(search_button)
        search_cancel_layout.addWidget(cancel_button)
        search_cancel_layout.setAlignment(Qt.AlignCenter)
        vert_layout1.addLayout(search_cancel_layout)

    def sendval(self):
        print(self.search_dir_te.text)

【问题讨论】:

    标签: python pyqt5


    【解决方案1】:

    您只需将initUI() 中的search_dir_te 更改为self.search_dir_te 即可在其他功能中访问。另外,在sendval()中加括号调用text()方法

    def initUI(self):
        search_dir_label = QLabel('Directory to Search')
        self.search_dir_te = QLineEdit()
        search_dir_layout = QHBoxLayout(self)
        search_dir_layout.addWidget(search_dir_label)
        search_dir_layout.addWidget(self.search_dir_te)
        vert_layout1.addLayout(search_dir_layout)
    
        search_button = QPushButton('Search')
        search_button.clicked.connect(self.sendval)   
        cancel_button = QPushButton('Cancel')
        search_cancel_layout = QHBoxLayout(self)
        search_cancel_layout.addWidget(search_button)
        search_cancel_layout.addWidget(cancel_button)
        search_cancel_layout.setAlignment(Qt.AlignCenter)
        vert_layout1.addLayout(search_cancel_layout)
    
    def sendval(self):
        print(self.search_dir_te.text())
    

    【讨论】:

    • 完美,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多