我正在使用QComplete用自动完成autocomplete_list
的列表填充QLineEdit小部件lineEdit1
。小部件成功地填充了自动完成列表中的数据。
但是,当我在lineEdit1
中输入以下任何文本时:
a
a1
a2
a3
a4
a5
然后按回车键,我得到以下错误信息:
Process finished with exit code -1073741819 (0xC0000005)
这里发生了什么?当我在小部件中输入"b"时,程序不会崩溃。当我在小部件中输入"1"时也可以。为什么当我在autocomplete_list
中输入"a"或5个项目中的任何一个时它会崩溃?
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def setupData(self):
self.lineEdit1 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit1.setObjectName("lineEdit1")
self.lineEdit1.returnPressed.connect(self.return_pressed)
self.autocomplete_list = ['a1', 'a2', 'a3', 'a4', 'a5']
self.completer = QtWidgets.QCompleter(self.autocomplete_list)
self.lineEdit1.setCompleter(self.completer)
def return_pressed(self):
user_input = self.lineEdit1.text()
updated_list = [x for x in self.autocomplete_list if x not in user_input]
print(updated_list)
self.completer = QtWidgets.QCompleter(updated_list)
self.lineEdit1.setCompleter(self.completer)
print('Gets to here')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.setupData()
MainWindow.show()
sys.exit(app.exec_())
我自己在C++中测试过逻辑,没有看到任何错误,我可以假设错误是由sip包装器引起的,该包装器保留了对旧QComplete指针的引用,当您建立新的QCompleter时,该指针会从内存中删除,从而生成分段错误(核心转储(。
另一方面,你的方法不是很优雅,我更喜欢使用模型来处理信息,然后只以简单的方式删除项目。
def setupData(self):
self.lineEdit1 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit1.setObjectName("lineEdit1")
self.lineEdit1.returnPressed.connect(self.return_pressed)
autocomplete_list = ['a1', 'a2', 'a3', 'a4', 'a5']
self.autocomplete_model = QtGui.QStandardItemModel()
for text in autocomplete_list:
self.autocomplete_model.appendRow(QtGui.QStandardItem(text))
self.completer = QtWidgets.QCompleter()
self.completer.setModel(self.autocomplete_model)
self.lineEdit1.setCompleter(self.completer)
def return_pressed(self):
user_input = self.lineEdit1.text()
items = self.autocomplete_model.findItems(user_input, QtCore.Qt.MatchContains)
for item in items:
self.autocomplete_model.takeItem(item.row())