2014-06-05 60 views
2

我有一個組合框,內容需要動態更改。我還需要知道用戶何時單擊組合框。當comboBox有內容時,它會觸發信號,但當它爲空時,我看不到任何信號。以下代碼是一個玩具示例,演示了對於空的comboBox,沒有信號會觸發。PyQt組合框小部件沒有信號時爲空

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']) 

如何檢測用戶是否與空閒組合框交互?

回答

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)