1

我正在使用 QCompleter 使用lineEdit1自动完成列表填充 QLineEdit 小部件autocomplete_list。小部件成功填充了自动完成列表中的数据。

但是,当我将以下任何文本输入lineEdit1

a
a1
a2
a3
a4
a5

然后按回车键,我收到以下错误消息:

Process finished with exit code -1073741819 (0xC0000005)

这里发生了什么?当我在小部件中输入“b”时,程序不会崩溃。当我在小部件中输入“1”时也很好。为什么当我输入“a”或 5 个项目中的任何一个时它会崩溃autocomplete_list

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_())

4

1 回答 1

1

我自己在 C++ 中测试了逻辑,我没有看到任何错误,我认为错误是由 sip 包装器引起的分段错误(核心转储)。

另一方面,您的方法不是很优雅,我更喜欢使用模型来处理信息,然后仅以简单的方式删除项目。

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())
于 2020-04-21T11:16:10.157 回答