专注于 pyqt Main 的事件处理 window

Fucos in event handling for pyqt Main window

我在 python 2.7 中使用 pyqt 4.10 并且我有主要的 window 并且我希望在 window 失去焦点时调用一个函数并再次获得它。

函数是:

def focusInEvent(self, event):
    print 'focus in event'
    conn = sqlite3.connect('storage/container.db')
    conn.row_factory = lambda c, row: row[0]
    c = conn.cursor()
    c.execute("SELECT category_name FROM categories")
    category_all = c.fetchall()
    conn.close()
    self.comboBox.clear()
    self.comboBox.addItems(category_all)
    super(mainWindow, self).focusInEvent(event)

更改 window 焦点没有任何作用,我的问题是..调用函数我应该使用一些信号,如 triggeredconnect?

或者函数作为一个事件工作,当条件(焦点位于)发生时已经触发

如果有信号可以使用。这是什么!

更新

试过这样做:

class EventFilter(QtCore.QObject):
    def __init__(self, parent=None):
        QtCore.QObject.__init__(self, parent)

    def eventFilter(self, obj, event):
        global comboBox
        if event.type() == QtCore.QEvent.ActivationChange:
            if self.parent().isActiveWindow():
                print "got the focus"
            conn = sqlite3.connect('storage/container.db')
            conn.row_factory = lambda c, row: row[0]
            c = conn.cursor()
            c.execute("SELECT category_name FROM categories")
            category_all = c.fetchall()
            conn.close()
            comboBox.clear()
            comboBox.addItems(category_all)
        return QtCore.QObject.eventFilter(self, obj, event)
mainWindow.installEventFilter(EventFilter(mainWindow))

它返回了错误:

got the focus
Traceback (most recent call last):
  File "C:\python\townoftechwarehouse\Warehouse.py", line 641, in eventFilter
    comboBox.clear()
NameError: global name 'comboBox' is not defined
got the focus

这意味着我成功地捕获了事件中的焦点,但是在事件过滤器的 class 之外看不到变量,如何调用其中的变量!?

我是通过一个函数来实现的,该函数在我获得焦点时执行我需要做的事情,这里是:

def refreshing():
    conn = sqlite3.connect('storage/container.db')
    conn.row_factory = lambda c, row: row[0]
    c = conn.cursor()
    c.execute("SELECT category_name FROM categories")
    category_all = c.fetchall()
    conn.close()
    self.comboBox.clear()
    self.comboBox.addItems(category_all)

然后我在事件过滤器中调用了它:

class EventFilter(QtCore.QObject):
    def __init__(self, parent=None):
        QtCore.QObject.__init__(self, parent)

    def eventFilter(self, obj, event):
        global comboBox
        if event.type() == QtCore.QEvent.ActivationChange:
            if self.parent().isActiveWindow():
                print "got the focus"
                refreshing()
        return QtCore.QObject.eventFilter(self, obj, event)

然后使用 mainWindow.installEventFilter(EventFilter(mainWindow))

将事件过滤器分配给我的主要 window

现在它完美运行,我可以在刷新功能中做任何我想做的事情