PyQt5:使Q完成器弹出窗口只读



我有一个QLineEdit的QComplete,它运行良好。

我只想让这个完成符只读。因此,用户只能看到匹配项,但不能选择其中的任何一个。没有突出显示,没有选定的项目。只应显示可见的匹配项列表。

我试了这么久,但还是被卡住了,无法完成任务。

这是代码:

from PyQt5.QtWidgets import QApplication, QWidget, QCompleter, QLineEdit, QVBoxLayout
from PyQt5.QtCore import Qt, QStringListModel
import sys
class MainWindow(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.testthislineEdit = QLineEdit()
temp_list = ['alpha', 'beta', 'boota', 'beita']
model = QStringListModel()
model.setStringList(temp_list)
completer = QCompleter()
completer.setFilterMode(Qt.MatchContains)
completer.setCaseSensitivity(Qt.CaseSensitivity(0))
completer.setModel(model)
layout = QVBoxLayout()
layout.addWidget(self.testthislineEdit)
self.setLayout(layout)
self.testthislineEdit.setCompleter(completer)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
try:
sys.exit(app.exec_())
except SystemExit:
print('Closing Window...')

实现这一点的一种方法是使用自定义项目视图和选择模型,并重新实现禁用所有默认选择、鼠标和键盘处理的方法。还需要确保自定义选择模型链接到完成者的内部代理模型。

以下是基于您的示例的工作演示:

from PyQt5.QtWidgets import QApplication, QWidget, QCompleter, QLineEdit, QVBoxLayout, QListView
from PyQt5.QtCore import Qt, QStringListModel, QItemSelectionModel, QAbstractProxyModel
import sys
class SelectionModel(QItemSelectionModel):
def select(self, *args, **kwargs):
# disable selection
pass
def setCurrentIndex(self, *args, **kwargs):
# disable current index
pass
class ListView(QListView):
def setSelectionModel(self, model):
# link custom selection model to completer proxy model
super().setSelectionModel(SelectionModel(model.model(), self))
def mousePressEvent(self, event):
# ignore mouse events
self.close()
class MainWindow(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.testthislineEdit = QLineEdit()
temp_list = ['alpha', 'beta', 'boota', 'beita']
model = QStringListModel()
model.setStringList(temp_list)
completer = QCompleter()
completer.setFilterMode(Qt.MatchContains)
completer.setCaseSensitivity(Qt.CaseSensitivity(0))
# set custom popup
completer.setPopup(ListView(self))
completer.setModel(model)
layout = QVBoxLayout()
layout.addWidget(self.testthislineEdit)
self.setLayout(layout)
self.testthislineEdit.setCompleter(completer)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
try:
sys.exit(app.exec_())
except SystemExit:
print('Closing Window...')

相关内容

  • 没有找到相关文章

最新更新