使用 PyQt6 中 KeyboardModifier 中未定义的键

问题描述 投票:0回答:1

我正在尝试使用 PyQt6 中定义的内置 KeyboardModifier 中未定义的键。我已经分配了 Ctrl、Shift、Alt 的功能。

我正在尝试使用字母键或数字键(不是 KeypadModifier 中定义的键,而是标准数字键)。我想知道是否可以创建一个自定义修饰符,或者使用另一种方法来检查按下了什么键以及 mousePressEvent。

我尝试了以下代码:

from PyQt6.QtWidgets import QWidget

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

    def mousePressEvent(self, event):
        # Check if the left mouse button is pressed
        if event.button() == Qt.LeftButton:
            # Check if the key "1" is pressed
            if event.key() == Qt.Key_1:
                print("Left mouse button and number key 1 pressed simultaneously")
                # Handle the event accordingly

        super().mousePressEvent(event)

    def keyPressEvent(self, event):
        # Check if the key pressed is the number key "1"
        if event.key() == Qt.Key_1:
            print("Number key 1 pressed")
            # Handle the event accordingly

        super().keyPressEvent(event)

但我收到此错误:

AttributeError: 'QMouseEvent' object has no attribute 'key'

所以我想知道是否还有其他方法可以实现这一目标。

提前致谢!

python pyqt pyqt6
1个回答
0
投票

您可以在类中创建描述 LMB 和 RMB 当前状态的属性,在

mousePressEvent
mouseReleaseEvent
中更改它们,以及在
keyPressEvent
中检查它们。

from PySide6.QtWidgets import QWidget, QApplication
from PySide6.QtCore import Qt
from PySide6.QtGui import QMouseEvent


class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.lmb_pressed = False  # is left mouse btn pressed?
        self.rmb_pressed = False  # is right mouse btn pressed?

    def mousePressEvent(self, event: QMouseEvent):
        if event.button() is Qt.MouseButton.LeftButton:
            self.lmb_pressed = True
        elif event.button() is Qt.MouseButton.RightButton:
            self.rmb_pressed = True
        super().mousePressEvent(event)

    def mouseReleaseEvent(self, event: QMouseEvent) -> None:
        if event.button() is Qt.MouseButton.LeftButton:
            self.lmb_pressed = False
        elif event.button() is Qt.MouseButton.RightButton:
            self.rmb_pressed = False
        super().mouseReleaseEvent(event)

    def keyPressEvent(self, event):
        # Check if LMB pressed
        if self.lmb_pressed:
            if event.key() == Qt.Key_1:
                print("Number key 1 pressed with LMB")

        # Check if the key pressed is the number key "1"
        elif event.key() == Qt.Key_1:
            print("Number key 1 pressed")
            # Handle the event accordingly

        super().keyPressEvent(event)
© www.soinside.com 2019 - 2024. All rights reserved.