Python中QLineEdit输入文本获取失败问题求助
解决PySide6中QLineEdit输入文本无法获取的问题
问题概述
使用PySide6开发时,QLineEdit控件可正常显示并允许输入,按下回车键能触发信号执行槽函数,但始终无法获取输入的文本内容,导致数据库查询不到对应记录。
错误原因
- 全局变量赋值错误:在
ci_widget类的__init__方法中,sys_cust_code = self.ui.ci_input.text()创建了局部变量,而非修改全局的sys_cust_code,导致槽函数中访问的全局变量始终为空字符串。 - 获取文本时机错误:初始化时就调用
text()获取内容,此时用户尚未输入任何文本,自然得不到有效内容。
修正后的代码
import os import sys import sqlite3 import PySide6 from PySide6.QtUiTools import QUiLoader from PySide6.QtCore import QSize from PySide6.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel from PySide6.QtWidgets import ( QApplication, QComboBox, QDataWidgetMapper, QDoubleSpinBox, QFormLayout, QLabel, QLineEdit, QMainWindow, QSpinBox, QWidget, ) loader = QUiLoader() basedir = os.path.dirname(__file__) class ci_widget(QWidget): def __init__(self): super().__init__() self.ui = loader.load( os.path.join(basedir, "windows/cust_input.ui"), None ) self.ui.setWindowTitle("Input Customer Code") # 绑定槽函数为类的方法,方便访问UI元素 self.ui.ci_input.returnPressed.connect(self.check_customer) self.ui.show() def check_customer(self): print("Customer Code Entered") # 在触发时才获取输入文本 sys_cust_code = self.ui.ci_input.text() print("Sys_cust_code = ", sys_cust_code) # 统一使用sqlite3连接数据库,避免冗余操作 connection_obj = sqlite3.connect(os.path.join(basedir, "databases/integrity.db")) cursor_obj = connection_obj.cursor() cursor_obj.execute('SELECT * FROM customer WHERE cust_code = ?', (sys_cust_code,)) customer_rec = cursor_obj.fetchone() sys_cust_found = "Y" if customer_rec else "N" print("sys_cust_found = ", sys_cust_found) print("sys_cust_code = ", sys_cust_code) connection_obj.close() # 关闭数据库连接,避免资源泄漏 app = QApplication(sys.argv) ui = ci_widget() app.exec()
关键修正点
- 将槽函数改为类的实例方法,直接通过
self.ui.ci_input.text()获取最新输入内容,无需依赖全局变量。 - 把获取文本的操作移到槽函数内部,确保在用户输入完成后再读取内容。
- 优化数据库连接逻辑,移除冗余的QtSql连接代码,添加连接关闭操作避免资源泄漏。
内容的提问来源于stack exchange,提问作者Walt Mayhew
相关产品推荐
相关产品推荐

