PyQt ComboBox为空时不发信号

2 投票
1 回答
766 浏览
提问于 2025-04-18 08:46

我有一个下拉框(comboBox),它的内容需要动态变化。我还想知道用户什么时候点击了这个下拉框。当下拉框里面有内容时,它会发出一些信号,但如果它是空的,我就看不到任何信号被触发。下面的代码是一个简单的例子,演示了当下拉框为空时,没有信号会被触发。

from PyQt4 import QtCore, QtGui
import sys

class Ui_Example(QtGui.QDialog):
    def setupUi(self, Dialog):
        self.dialog = Dialog
        Dialog.setObjectName("Dialog")
        Dialog.resize(300,143)
        self.comboBox = QtGui.QComboBox(Dialog)
        self.comboBox.setGeometry(QtCore.QRect(60,20,230,20))
        self.comboBox.setObjectName("comboBox")

class Ui_Example_Logic(QtGui.QMainWindow):
    def __init__(self):
        super(Ui_Example_Logic, self).__init__()

    def create_main_window(self):
        self.ui = Ui_Example()
        self.ui.setupUi(self)
        self.ui.comboBox.highlighted.connect(self.my_highlight)
        self.ui.comboBox.activated.connect(self.my_activate)

    def my_highlight(self):
        print "Highlighted"

    def my_activate(self):
        print "Activated"

if __name__ == '__main__':
    APP = QtGui.QApplication([])
    WINDOW = Ui_Example_Logic()
    WINDOW.create_main_window()
    WINDOW.show()
    sys.exit(APP.exec_())

举个例子,如果在 create_main_window 函数里面添加下面这行代码,"activated""highlighted" 会在预期的事件中打印出来,但现在的代码(下拉框是空的)什么也不会打印。

self.ui.comboBox.addItems(['a', 'b'])

我该如何检测用户在下拉框为空的时候是否有进行操作呢?

1 个回答

1

如果你的 combobox 是空的,就不会发出任何信号。不过,你可以为这个下拉框安装一个事件过滤器,并重新实现 eventfilter 方法(链接)。首先,创建过滤器:

class MouseDetector(QtCore.QObject):
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.MouseButtonPress and obj.count() == 0:
            print 'Clicked'
        return super(MouseDetector, self).eventFilter(obj, event)

当用户在空的 comboBox 上按下鼠标按钮时,它会打印出 Clicked,这个下拉框是在 Ui_Example 中创建的。接下来,安装事件:

class Ui_Example(QtGui.QDialog):
    def setupUi(self, Dialog):
        self.dialog = Dialog
        Dialog.setObjectName("Dialog")
        Dialog.resize(300,143)
        self.comboBox = QtGui.QComboBox(Dialog)
        self.comboBox.setGeometry(QtCore.QRect(60,20,230,20))
        self.comboBox.setObjectName("comboBox")

        self.mouseFilter = MouseDetector()
        self.comboBox.installEventFilter(self.mouseFilter)

撰写回答