pyqt主窗口事件处理中的Fucos

时间:2018-03-25 11:55:12

标签: python pyqt focus

我在python 2.7中使用pyqt 4.10并且我有主窗口,我希望在窗口失去焦点并再次获取它时调用一个函数。

功能是:

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)

更改窗口焦点什么都不做,我的问题是..调用函数我应该使用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

这意味着我成功地抓住了事件中的焦点,但是无法从事件过滤器类之外看到变量,如何在那里调用var!?

1 个答案:

答案 0 :(得分:0)

我通过拥有一个函数来完成它,当我得到focusIn时,它执行我需要做的事情,这里是:

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

将事件过滤器分配到我的主窗口

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