PyQt:如何在子类 QWidget 中接收键盘事件?
也许这个问题已经被问过很多次了,但我找不到解决方案。
我有一个对话框:
class PostDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog() #code from designer!!
self.ui.setupUi(self)
self.ui.plainTextEdit = ContentEditor()
该对话框有一个来自设计器的 QPlainTextEdit。
我需要覆盖 QPlainTextEdit 的 keyPress 和 keyRelease 。
所以我对它进行了子类化:
class ContentEditor(QtGui.QPlainTextEdit):
def __init__(self, parent=None):
QtGui.QPlainTextEdit.__init__(self, parent)
def keyPressEvent(self, event):
print "do something"
但 ContentEditor.keyPressEvent 从未被调用!为什么?
Maybe this is been asked many times, but i can't find a solution.
I have a dialog:
class PostDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog() #code from designer!!
self.ui.setupUi(self)
self.ui.plainTextEdit = ContentEditor()
This dialog has a QPlainTextEdit from the designer.
I need to override keyPress and keyRelease of that QPlainTextEdit.
So i have subclassed it:
class ContentEditor(QtGui.QPlainTextEdit):
def __init__(self, parent=None):
QtGui.QPlainTextEdit.__init__(self, parent)
def keyPressEvent(self, event):
print "do something"
but ContentEditor.keyPressEvent is never called! Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用 installEventFilter 来实现此目的:
这看起来像:
I recommend using installEventFilter for this purpose:
This would look like:
您想要完成的任务最好通过在 Qt Designer 中提升将 QPlainTextEdit 小部件提升到您的子类 ContentEditor 来完成。
Qt 文档
在“升级的小部件”对话框中:
“提升班级名称”:ContentEditor
“头文件”:your_python_module_name.h
What you're trying to accomplish is better done by promoting in Qt Designer the QPlainTextEdit widget to your subclass ContentEditor.
Qt documentation
In the "Promoted Widgets" Dialog:
"Promote class name": ContentEditor
"Header file": your_python_module_name.h
可能您需要调用 QWidget 的 setFocusPolicy 方法来接收 KeyPress 事件。
来自 QWidget 方法 keyPressEvent:
May be you need to call method
setFocusPolicy
of QWidget to receive a KeyPress Event.From API docs of QWidget for the method keyPressEvent:
您可能只需要交换以下两行:
如果您像这样编写:
您确保在 UI 设置之前绑定您的自定义小部件。否则,您只是替换对已初始化对象的引用。
You'll probably just need to swap the following two lines:
If you write it like this:
you make sure your custom widget gets bound before the UI gets setup. Otherwise you're just replacing a reference to an already initialised object.