问题描述
我正在编写一个 Python 应用程序,用户可以在其中在 QInputDialog 中输入一个字符串.如何使用 QCompleter 使输入更容易?
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?
我已经在不同的网站上搜索并阅读了文档https://doc.qt.io/qt-5/qcompleter.html#详情但找不到任何解决此问题的方法.
I've already been searching on different websites and read the doc fromhttps://doc.qt.io/qt-5/qcompleter.html#detailsbut couldn't find any help for this problem.
在我看来,QCompleter 似乎只适用于 QLineEdit 和 QComboBox.(请证明我错了)
To me, it seems like the QCompleter is only available for QLineEdit and QComboBox. (Please proof me wrong)
ian, okPressed = QInputDialog.getText(self, "IAN", "Please enter IAN:")
如果有人可以向我展示一些如何处理此问题的代码示例,那将对我有很大帮助.
It would help me a lot if anyone could show me some code examples how to deal with this problem.
如果不能在 QInputDialog 中使用 QCompleter,你们有解决方法的想法吗?
If it's not possible to use the QCompleter within the QInputDialog, do you guys have an idea for a workaround?
非常感谢 =)
推荐答案
有两种可能的解决方案:
There are 2 possible solutions:
- 通过父级获取
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_())
这篇关于如何将 QCompleter 与 InputDialog 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!