我有一个组合框,其内容需要动态更改。我还需要知道用户何时单击组合框。当 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'])
当 comboBox 为空时,如何检测用户是否与它进行了交互?
请您参考如下方法:
如果您的 combobox 为空,则不会发出任何信号。但是您可以为组合框installEventFilter 并重新实现eventfilter ( link )。首先,创建过滤器:
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)
当用户在 Ui_Example 中创建的空 comboBox 上按下鼠标按钮时,将打印 Clicked。然后,安装事件:
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)
