我是 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)
您必须实现
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_())
输出:
lineedit
pushbutton
combobox
pushbutton
lineedit
一个问题, 为什么当我执行以下操作时它不起作用?
导入系统 从 PyQt5 导入 QtWidgets
class Main(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Qt Testing")
self.setGeometry(0, 0, 640, 120)
h = QtWidgets.QHBoxLayout()
self.w = QtWidgets.QLineEdit("one")
h.addWidget(self.w)
self.w = QtWidgets.QLineEdit("two")
h.addWidget(self.w)
self.setLayout(h)
def focusInEvent(self, event):
print("in")
self.setStyleSheet("background-color: yellow; color: red;")
super().focusInEvent(event)
def focusOutEvent(self, event):
print("out")
self.setStyleSheet("background-color: white; color: black;")
super().focusOutEvent(event)
app = QtWidgets.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec())