问题描述:

I have a comboBox and the contents need to change dynamically. I also need to know when the user clicks on the comboBox. When the comboBox has content, it will fire signals, but when it's empty I don't see any signals fired at all. The following code is a toy example demonstrating that for an empty comboBox, no signal will fire.

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_())

So for example, if the line below is added to the create_main_window function, "activated" and "highlighted" will print out on expected events, but as the code is now (with the comboBox empty) nothing will print.

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

How can I detect if the user has interacted with the comboBox when it is empty?

网友答案:

If your combobox is empty, no signal will be emitted. But you can installEventFilter for your combobox and reimplement eventfilter (link). First, create filter:

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)

It will be print Clicked when user press mouse button on empty comboBox, created inside Ui_Example. Then, install event:

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)
相关阅读:
Top