python - 如何在 PyQt 中获取之前激活的小部件?

标签 python user-interface pyqt

我有一个按钮和两个表格小部件。按下按钮会执行两种不同的操作,具体取决于在按下按钮之前激活了哪个表格小部件。如何获得正确的小部件?

最佳答案

例如,您可以使用 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_())

关于python - 如何在 PyQt 中获取之前激活的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17376085/

相关文章:

python - 在 PyQt 中使用信号在类之间传递数据

Python:如何创建目录并在必要时覆盖现有目录?

python - Python 段错误

python - 无法从类中抓取文本 (BeautifulSoup)

user-interface - Flyspell 正确单词的用户交互改进

linux - Linux 下 Haskell 的图形化 shell

qt - 如何在不缩放笔宽的情况下在 QGraphicsScene 上绘图?

python - 将 10 位无符号整数转换为 python 中的有符号整数

html - 如何在密码类型的输入元素中设置文本位置?

qt - 将 QDialog 嵌入到 QWidget 中的简单方法