2017-01-23 1 views
0

私はPyQtが初めてです。 QtDeveloperで3つのコントロールを持つフォームを設計しました。プッシュボタン1つ、コンボボックス1つ、行編集1つ。私のUIフォームの行編集ウィジェットの名前はmyLineEditです。どのQwidgetにフォーカスがあるのか​​を知りたい(QLineEditまたはQComboBox)。私はインターネットから入手したコードを実装します。コードを実行すると、別の行の編集が作成され、正常に動作します。しかし、私は、.uiフォームで作成されたmyLineEditウィジェットにfocusInEventを与えたいと思います。私のコードが与えられます。助けてください。uiフォームでどの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

それは魅力のように働きました。大丈夫です。 –

関連する問題