我正在编写一个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,那么你们是否有解决办法?
非常感谢=)
答案 0 :(得分:1)
有2种可能的解决方案:
QInputDialog
通过小部件之间的父子关系获取findChild()
: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_())