Skip to content Skip to sidebar Skip to footer

How To Use Qcompleter With An Inputdialog?

I am writing a Python Application where the user can enter a String in an QInputDialog. How can i use the QCompleter to make Inputs easier? I've already been searching on different

Solution 1:

There are 2 possible solutions:

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_())
  • Do not use the static method and create the QInputDialog with the same elements:
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_())

Post a Comment for "How To Use Qcompleter With An Inputdialog?"