在PyQt5中单击按钮时如何读取QLineEdit和QCheckBox值?

时间:2020-02-21 13:09:41

标签: python pyqt5

我正在尝试使用下面的代码,但是在执行时说“ Python停止工作”并重新启动外壳。基本上是在单击按钮时尝试从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)

1 个答案:

答案 0 :(得分:0)

您只需要将search_dir_te中的self.search_dir_te更改为initUI(),以便可以在其他功能中对其进行访问。另外,添加括号以在text()

中调用方法sendval()
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())