問題描述
我正在編寫一個 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 from https://doc.qt.io/qt-5/qcompleter.html#details but 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 一起使用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!