QComboBox 点击事件 [英] QComboBox click event
问题描述
我一直试图在 PyQt5 中获取一个 QComboBox
以从数据库表中填充.问题是试图找到一种方法来识别点击事件.
I have been trying to get a QComboBox
in PyQt5 to become populated from a database table. The problem is trying to find a method that recognizes a click event on it.
在我的 GUI 中,我的组合框最初是空的,但是在单击它时,我希望单击事件激活我的方法以与数据库通信并填充下拉列表.到目前为止,组合框的点击事件似乎没有内置的事件处理程序.我希望我错了.我希望有人能够告诉我有一种方法可以做到这一点.
In my GUI, my combo-box is initially empty, but upon clicking on it I wish for the click event to activate my method for communicating to the database and populating the drop-down list. It seems so far that there is no built-in event handler for a click-event for the combo-box. I am hoping that I am wrong on this. I hope someone will be able to tell me that there is a way to do this.
我能在这里找到的关于我的用例的最好的文章来自这个链接,引用了 PyQt4 QComboBox
:
The best article I could find on my use-case here is from this link referring to PyQt4 QComboBox
:
我还发现了另一个包含 QComboBox
精美图片的链接.第一个元素似乎是一个标签,后跟一个列表:
I also found another link that contains a nice image of a QComboBox
.
The first element seems to be a label followed by a list:
推荐答案
您可以覆盖 showPopup 方法来实现这一点,无论下拉列表如何打开(即通过鼠标、键盘或快捷方式),它都可以工作:
You can override the showPopup method to achieve this, which will work no matter how the drop-down list is opened (i.e. via the mouse, keyboard, or shortcuts):
from PyQt5 import QtCore, QtWidgets
class ComboBox(QtWidgets.QComboBox):
popupAboutToBeShown = QtCore.pyqtSignal()
def showPopup(self):
self.popupAboutToBeShown.emit()
super(ComboBox, self).showPopup()
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.combo = ComboBox(self)
self.combo.popupAboutToBeShown.connect(self.populateConbo)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.combo)
def populateConbo(self):
if not self.combo.count():
self.combo.addItems('One Two Three Four'.split())
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
但是,对于您的特定用例,我认为更好的解决方案可能是设置 QSqlQueryModel 在组合框上,以便自动从数据库更新项目.
However, for your particular use-case, I think a better solution might be to set a QSqlQueryModel on the combo-box, so that the items are updated from the database automatically.
这篇关于QComboBox 点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!