如何在PyQt中获取先前激活的小部件?

3

我有一个按钮和两个表格小部件。按下按钮会根据哪个表格小部件在按钮推动之前被激活而执行两个不同的操作。如何获取正确的小部件?

1个回答

2

例如,您可以使用focusInEvent来存储已激活的小部件,并在按下按钮时返回它,就像这样:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtGui, QtCore

class MyTableWidget(QtGui.QTableWidget):
    focusIn = QtCore.pyqtSignal(QtCore.QObject)

    def __init__(self, parent=None):
        super(MyTableWidget, self).__init__(parent)

    def focusInEvent(self, event):
        self.focusIn.emit(self)

        return super(MyTableWidget, self).focusInEvent(event)

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)      

        self.lastFocusedTableWidget = None

        self.tableWidgetFirst  = MyTableWidget(self)
        self.tableWidgetFirst.setObjectName("tableWidgetFirst")
        self.tableWidgetFirst.focusIn.connect(self.on_tableWidget_focusIn)

        self.tableWidgetSecond = MyTableWidget(self)
        self.tableWidgetSecond.setObjectName("tableWidgetSecond")
        self.tableWidgetSecond.focusIn.connect(self.on_tableWidget_focusIn)

        self.pushButtonLastFocused = QtGui.QPushButton(self)
        self.pushButtonLastFocused.setText("Print the last focused QTableWidget!")
        self.pushButtonLastFocused.clicked.connect(self.on_pushButtonLastFocused_clicked)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.tableWidgetFirst)
        self.layoutVertical.addWidget(self.tableWidgetSecond)
        self.layoutVertical.addWidget(self.pushButtonLastFocused)

    @QtCore.pyqtSlot(QtCore.QObject)
    def on_tableWidget_focusIn(self, obj):
        self.lastFocusedTableWidget = obj

    @QtCore.pyqtSlot()
    def on_pushButtonLastFocused_clicked(self):
        print self.lastFocusedTableWidget.objectName()

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(333, 111)
    main.show()

    sys.exit(app.exec_())

你能解释一下 focusIn 信号是什么时候被传输的吗? - IordanouGiannis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接