PyQt ComboBox小部件在空时不发出信号

时间:2014-06-05 17:29:14

标签: python pyqt4

我有一个comboBox,内容需要动态更改。我还需要知道用户何时单击comboBox。当comboBox有内容时,它会触发信号,但是当它没空时,我根本看不到任何信号。以下代码是一个玩具示例,演示了对于空的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"将打印出预期的事件,但现在代码是(使用comboBox)空的)什么都不打印。

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

如何在空的时候检测用户是否与comboBox进行了交互?

1 个答案:

答案 0 :(得分:1)

如果combobox为空,则不会发出任何信号。但是你可以installEventFilter为你的组合框并重新实现eventfilterlink)。首先,创建过滤器:

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)

当用户在Clicked内创建的空comboBox上按鼠标按钮时,将会打印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)