如何将 QCompleter 与 InputDialog 一起使用?

How to use QCompleter with an InputDialog?

我正在编写一个 Python 应用程序,用户可以在其中在 QInputDialog 中输入字符串。我如何使用 QCompleter 使输入更容易?

我已经在不同的网站上搜索并阅读了来自 https://doc.qt.io/qt-5/qcompleter.html#details 但找不到解决此问题的任何帮助。

对我来说,QCompleter 似乎只适用于 QLineEdit 和 QComboBox。 (请证明我错了)

ian, okPressed = QInputDialog.getText(self, "IAN", "Please enter IAN:")

如果有人能告诉我一些代码示例如何处理这个问题,那将对我有很大帮助。

如果无法在 QInputDialog 中使用 QCompleter,你们有解决方法吗?

非常感谢=)

有 2 种可能的解决方案:

from PyQt5 import QtCore, QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        button = QtWidgets.QPushButton("Press me", clicked=self.onClicked)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button)

    @QtCore.pyqtSlot()
    def onClicked(self):
        QtCore.QTimer.singleShot(0, self.onTimeout)
        ian, okPressed = QtWidgets.QInputDialog.getText(
            self, "IAN", "Please enter IAN:"
        )

    @QtCore.pyqtSlot()
    def onTimeout(self):
        dialog = self.findChild(QtWidgets.QInputDialog)
        if dialog is not None:
            le = dialog.findChild(QtWidgets.QLineEdit)
            if le is not None:
                words = ["alpha", "omega", "omicron", "zeta"]
                completer = QtWidgets.QCompleter(words, le)
                le.setCompleter(completer)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())
  • 不要使用静态方法并使用相同的元素创建 QInputDialog
from PyQt5 import QtCore, QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        button = QtWidgets.QPushButton("Press me", clicked=self.onClicked)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button)

    @QtCore.pyqtSlot()
    def onClicked(self):
        dialog = QtWidgets.QInputDialog(self)
        dialog.setWindowTitle("IAN")
        dialog.setLabelText("Please enter IAN:")
        dialog.setTextValue("")
        le = dialog.findChild(QtWidgets.QLineEdit)
        words = ["alpha", "omega", "omicron", "zeta"]
        completer = QtWidgets.QCompleter(words, le)
        le.setCompleter(completer)

        ok, text = (
            dialog.exec_() == QtWidgets.QDialog.Accepted,
            dialog.textValue(),
        )
        if ok:
            print(text)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())