我应该使用 KeyPressEvent 还是 QAction 来实现按键?
在 Qt 中,无论是实现 keyPressEvent 还是创建 QAction 并为其分配组合键,都可以让我根据键盘进行操作。
通常首选以下哪种方法?
In Qt, either implementing keyPressEvent or creating a QAction and assigning it a key combination allow me to act based on the keyboard.
Which of these methods is generally preferred?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只要您想要的按键序列触发的同一事件可能通过其他方式(例如菜单、工具栏或其他按钮)触发,您就应该使用 QAction。这样您就可以在几个应该执行相同技巧的小部件上使用相同的操作。
摘自 QAction 文档:
You should use QAction whenever the same event that is triggered by the key sequence you want may be triggered through other ways like from a menu, toolbar or other buttons. This way you can use the same action on several widgets that should do the same trick.
Excerpt from QAction doc:
我更愿意覆盖
keyPressEvent
。我不喜欢 QAction “位于某处”的想法。只需覆盖keyPressedEvent
即可。我通常使用开关盒来检查按下的键。如果您不想禁用按键的标准行为,请不要忘记调用基类的 keyPressEvent。此外,您还可以检查在发生keyPressEvent
时是否按下了“修饰符”。 (例如 Shift 或 Ctrl)。恕我直言,出于一般目的,覆盖keyPressEvent
比创建不可见的秘密操作更好,除非您希望应用程序包含所有对用户可见的操作。I'd prefer to overwrite the
keyPressEvent
. I don't like the idea of aQAction
"lying around somewhere". Just overwrite thekeyPressedEvent
. I usually do it with a switch-case in which I check the pressed key. Just don't forget to call the keyPressEvent of the base class if you don't want to disable the standard behaviour of a key. Additionally you can check if a "modifier" is pressed while akeyPressEvent
occurs. (e.g. Shift or Ctrl). IMHO for general purposes overwriting thekeyPressEvent
is better than creating invisible, secret actions, unless you want your application to contain all those actions visible for the user.取决于你需要它做什么。
是否是类似菜单的操作,也可以由菜单、按钮、工具栏触发,然后选择 QAction。特别是如果此操作应该在整个程序中起作用,而不仅仅是在单个小部件中。
它更像是单个小部件中的本地活动(例如控制游戏中的移动),我会使用按键事件。
Would depend on what you need it for.
Is it for a menu like action that may be triggered by a menu, button, toolbar too, then go for the QAction. Especially if this action should work all over your program, not only in a single widget.
Is it more like a local activity in a single widget (say for example controlling movement in a game), I would use the keypress event.