我有一个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
为空,则不会发射任何信号。但是您可以为组合框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)
当用户在
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)
关于python - PyQt ComboBox小部件不为空时发信号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24066518/