如何根据文本输入过滤 PyQt QCombobox 项目?
我需要一个 QCombox,它根据文本输入过滤项目。如果我将 QCombobox 设置为可编辑,则用户可以插入文本并自动创建 QCompleter。但这些项目没有被过滤,我不希望用户添加新项目。
是否有可能将此功能添加到 QCombobox 中?
I need a QCombox which Items are filtered based on the text input. If I set the QCombobox editable, the user can insert text and the QCompleter is automatically created. But the items are not filtered and I don’t want the user to add new Items.
Is there any possibility to add this functionality to the QCombobox?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在组合框内搜索。终于有了一个好的解决方案。谢谢你们!!这对我帮助很大。
这是 PyQt5 调整后的代码:
searching inside the combobox. Finally a good solution. Thank you guys!! It helped me a lot.
And here is the adjusted code to PyQt5:
试试这个代码,是我在我的项目中使用的代码
Try this code, is something i used in a project of mine
感谢您的精彩回答,我也遇到了同样的问题。
它工作得很好,但迫使您提供外部模型,这是不必要的。
我扩展了代码,使其也可以使用组合框已提供的内部标准模型。
还完成了一些清理和文档...
Thanks for the nice answer, I had the same problem.
It works nicely, but forces you to supply an external model, which is unnecessary.
I extended the code to also work with the internal standard model already supplied by the combobox.
Also some cleanup and documentation has been done...
发布的两个答案都是正确的,但是它们有一个小错误,其中通过键入然后单击选择来过滤组合框中的选项不会导致激活信号触发。您可以通过将
self.activated[str].emit(self.itemText(index))
放置在on_completer_activated
中的self.setCurrentIndex( 之后的行) 来解决此问题索引)
。当您从完成器中选择一个项目时,这会触发一个激活的信号,其中包含所单击的项目的名称。
Both answers posted are correct, however they have a small bug wherein filtering the options in the combobox by typing then clicking a selection doesn't cause an activation signal to fire. You can fix this by placing
self.activated[str].emit(self.itemText(index))
inon_completer_activated
, on the line afterself.setCurrentIndex(index)
.This fires an activated signal when you select an item from the completer, which contains the name of the item that was clicked.
如果有人感兴趣:pyqt5 的相同代码
if someone is interested: the same code for pyqt5
这很容易。
您还可以使用 Qt.MatchContain 方法。
访问https://doc.qt.io/qt-6/qt.html 了解更多详情。
It's very easy.
You can also use Qt.MatchContain method.
visit https://doc.qt.io/qt-6/qt.html for more details.