QComboBox单击事件 [英] QComboBox click event

查看:1094
本文介绍了QComboBox单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在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:

  • dropdown event/callback in combo-box in pyqt4

我还找到了另一个链接,其中包含 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:

  • Catch mouse button pressed signal from QComboBox popup menu

推荐答案

您可以覆盖 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_())

但是,针对您的特定用途-case,我认为更好的解决方案可能是在组合上设置 QSqlQueryModel -box,以便自动从数据库中更新项目。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆