1

我刚开始使用 PyQt5,这里有一个小文件:

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setMinimumWidth(350)

        layout = QGridLayout()
        self.setLayout(layout)

        self.completer = QCompleter()
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.completer.setMaxVisibleItems(10)

        self.lineedit = QLineEdit()
        self.lineedit.setCompleter(self.completer)
        self.lineedit.setFixedHeight(30)
        self.lineedit.setFixedWidth(300)
        #self.lineedit.returnPressed.connect(self.show_selected)
        self.lineedit.textChanged.connect(self.text_changed)

        layout.addWidget(self.lineedit,0,0)

    def text_changed(self):
        #the function get_request returns a list of names taken from 
        #a database e.g ['matthew','mark','morris','mickey']
        vals = self.get_request(self.lineedit.text())
        self.completer.setModel(vals)

app = QApplication(sys.argv)

screen = Window()

sys.exit(app.exec_())

我的问题是这个错误:

TypeError: setModel(self, QAbstractItemModel): argument 1 has unexpected type 'list'

每次我运行上面的代码。所以我的问题是:我在这里做错了什么,我刚从 pyqt5 开始,作为我的第一个程序,我立即得到这个错误。作为旁注,当我使用固定列表和把它放在QCompleter程序工作的构造函数中,但这不是一个选项,因为我需要随着用户输入而改变结果

4

1 回答 1

2

您需要通过 setStringList() 更新 QStringListModel

import sys
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget, QGridLayout, QCompleter
from PyQt5.QtCore import Qt

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setMinimumWidth(350)

        layout = QGridLayout()
        self.setLayout(layout)

        self.completer = QCompleter([])  # Initialze with a list...to establish QStringListModel
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.completer.setMaxVisibleItems(10)

        self.lineedit = QLineEdit()
        self.lineedit.setCompleter(self.completer)
        self.lineedit.setFixedHeight(30)
        self.lineedit.setFixedWidth(300)
        self.lineedit.textChanged.connect(self.text_changed)
        layout.addWidget(self.lineedit,0,0)

    def get_request(self, line_text):
        if not line_text:
            return []
        char = line_text[0]
        if char == 'a':
            return ['aaa', 'abba', 'abby']
        if char == 'm':
            return ['matthew','mark','morris','mickey']
        return ['foo', 'bar', 'baz']

    def text_changed(self):
        #the function get_request returns a list of names taken from
        #a database e.g ['matthew','mark','morris','mickey']
        vals = self.get_request(self.lineedit.text())

        model = self.completer.model()
        model.setStringList(vals)  # Updated the QStringListModel string list

app = QApplication(sys.argv)

screen = Window()
screen.show()

sys.exit(app.exec_())
于 2018-09-29T17:08:48.800 回答