如何知道ui形式的哪个qwidget在pyqt中得到了关注

Mar*_*aks 2 python pyqt qwidget pyqt4 pyqt5

我是PyQt的新手.我在QtDeveloper中设计了一个有三个控件的表单.一个按钮,一个组合框和一行编辑.我的ui表单中的行编辑小部件的名称是myLineEdit.我想知道哪个Qwidget得到了关注(QLineEdit或QComboBox).我实现从互联网获得的代码.代码运行时,会创建一个单独的行编辑,它可以正常工作.但我想将focusInEvent提供给以.ui格式创建的myLineEdit小部件.我的代码是给出的.请帮忙.

class MyLineEdit(QtGui.QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)
    def focusInEvent(self, event):
        print 'focus in event'
        self.clear()
        QLineEdit.focusInEvent(self, QFocusEvent(QEvent.FocusIn))

class MainWindow(QtGui.QMainWindow,Ui_MainWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.myLineEdit = MyLineEdit(self)
Run Code Online (Sandbox Code Playgroud)

eyl*_*esc 7

您必须实现该eventFilter方法并将此属性启用到所需的小部件:

{your widget}.installEventFilter(self)
Run Code Online (Sandbox Code Playgroud)

eventFilter方法具有事件的对象和类型作为信息.

import sys
from PyQt5 import uic
from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QApplication, QWidget

uiFile = "widget.ui"  # Enter file here.

Ui_Widget, _ = uic.loadUiType(uiFile)


class Widget(QWidget, Ui_Widget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.setupUi(self)
        self.lineEdit.installEventFilter(self)
        self.pushButton.installEventFilter(self)
        self.comboBox.installEventFilter(self)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.FocusIn:
            if obj == self.lineEdit:
                print("lineedit")
            elif obj == self.pushButton:
                print("pushbutton")
            elif obj == self.comboBox:
                print("combobox")
        return super(Widget, self).eventFilter(obj, event)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

输出继电器:

lineedit
pushbutton
combobox
pushbutton
lineedit
Run Code Online (Sandbox Code Playgroud)