2017-01-23 29 views
0

我是PyQt的新手。我在QtDeveloper中设计了一个有三个控件的表单。一个按钮,一个组合框和一行编辑。我的UI格式中的行编辑小部件的名称是myLineEdit。我想知道哪个Qwidget获得焦点(QLineEdit或QComboBox)。我执行从互联网上获得的代码。代码运行时,会创建一个单独的行编辑,并且工作正常。但是我想将focusInEvent赋给以.ui形式创建的myLineEdit小部件。我的代码给出。请帮忙。如何知道用户界面中的哪个qwidget获得了pyqt的焦点

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) 

回答

2

您必须实现eventFilter方法并启用此属性所需要与部件:

{your widget}.installEventFilter(self) 

的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_()) 

enter image description here

输出继电器:

lineedit 
pushbutton 
combobox 
pushbutton 
lineedit 
+0

它的工作就像一个魅力。谢谢亲爱的。 –

相关问题