1

我正在编写一个 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,你们有解决方法的想法吗?

非常感谢 =)

4

1 回答 1

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_())
于 2019-07-17T13:42:05.677 回答