• PySide6入门实战之五 | 信号与槽函数之鼠标、键盘等事件


    在这里插入图片描述


    前言
    PySide6 中处理鼠标事件和键盘事件是非常常见的需求。
    要处理鼠标事件,你可以重载 mousePressEventmouseReleaseEventmouseMoveEvent 等事件处理方法。
    处理键盘事件也很类似,你需要重载 keyPressEventkeyReleaseEvent 方法。


    🚀🚀🚀 Pyside6实战教程专栏目录入口:点击跳转


    一、前期准备

    我们采用Pyside入门实战之四中通过QTDesigner创建的界面,具体由两个Label和一个Button组件构成(含背景),如下所示:
    在这里插入图片描述

    import sys
    from PySide6.QtWidgets import QMainWindow, QApplication
    
    from ui_main import Ui_MainWindow
    
    
    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        win = MainWindow()
        win.show()
        app.exec()
    

    二、处理鼠标事件

    import sys
    from PySide6.QtWidgets import QMainWindow, QApplication
    from PySide6 import QtGui
    from PySide6.QtCore import Qt
    
    from ui_main import Ui_MainWindow
    
    
    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)
            
    		# 开启鼠标追踪
            self.setMouseTracking(True)  
    
        def mousePressEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.label.setText("点击了鼠标左键")
    
        def mouseMoveEvent(self, event: QtGui.QMouseEvent):
            self.label_2.setText(f"鼠标移动  x:{event.x()} y:{event.y()}")
    
        def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.label("释放了鼠标左键")
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        win = MainWindow()
        win.show()
        app.exec()
    

    2.1 隐藏窗口边框

    很多人在制作自己的GUI界面时,往往会隐藏界面窗口默认的边框,以达到美观的效果。其功能实现非常简单,仅需要添加一行代码即可。

    import sys
    from PySide6.QtWidgets import QMainWindow, QApplication
    from PySide6.QtCore import Qt
    
    from ui_main import Ui_MainWindow
    
    
    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)
            # 隐藏窗口边框
            self.setWindowFlags(Qt.FramelessWindowHint)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        win = MainWindow()
        win.show()
        app.exec()
    

    在这里插入图片描述
    这样就会出现一个问题GUI界面位置固定,鼠标无法拖动。那么就需要鼠标事件来实现拖动窗口的功能。

    2.2 鼠标拖动窗口

    核心代码:

    def mousePressEvent(self, event: QtGui.QMouseEvent):
        if event.button() == Qt.LeftButton:
            self.mouse_start_pt = event.globalPosition().toPoint()
            self.window_pos = self.frameGeometry().topLeft()
            self.drag = True
    
    def mouseMoveEvent(self, event: QtGui.QMouseEvent):
        if self.drag:
            distance = event.globalPosition().toPoint() - self.mouse_start_pt
            self.move(self.window_pos + distance)
    
    def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
        if event.button() == Qt.LeftButton:
            self.drag = False
    

    2.3 完整代码

    import sys
    from PySide6.QtWidgets import QMainWindow, QApplication
    from PySide6 import QtGui
    from PySide6.QtCore import Qt
    
    from ui_main import Ui_MainWindow
    
    
    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)
            # 隐藏窗口边框
            self.setWindowFlags(Qt.FramelessWindowHint)
    
        def mousePressEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.mouse_start_pt = event.globalPosition().toPoint()
                self.window_pos = self.frameGeometry().topLeft()
                self.drag = True
    
        def mouseMoveEvent(self, event: QtGui.QMouseEvent):
            if self.drag:
                distance = event.globalPosition().toPoint() - self.mouse_start_pt
                self.move(self.window_pos + distance)
    
        def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.drag = False
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        win = MainWindow()
        win.show()
        app.exec()
    

    在这里插入图片描述

    二、处理键盘事件

    完成上述功能后,又一个新的问题抛出,我们将窗口边框隐藏后,那我们将如何关闭窗口呢?

    我们当然可以使用Button触发close事件关闭窗口,代码如下:

    import sys
    from PySide6.QtWidgets import QMainWindow, QApplication
    from PySide6 import QtGui
    from PySide6.QtCore import Qt
    
    from ui_main import Ui_MainWindow
    
    
    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)
            # 隐藏窗口边框
            self.setWindowFlags(Qt.FramelessWindowHint)
    
            self.btn_1.setText("关闭窗口") # 修改按钮上的文字显示
            self.btn_1.clicked.connect(self.close) # 点击触发close事件
    
        def mousePressEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.mouse_start_pt = event.globalPosition().toPoint()
                self.window_pos = self.frameGeometry().topLeft()
                self.drag = True
    
        def mouseMoveEvent(self, event: QtGui.QMouseEvent):
            if self.drag:
                distance = event.globalPosition().toPoint() - self.mouse_start_pt
                self.move(self.window_pos + distance)
    
        def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.drag = False
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        win = MainWindow()
        win.show()
        app.exec()
    

    核心代码即为这两行。其中btn_1为自定义按钮命名(根据自己命名更改)。

    self.btn_1.setText("关闭窗口") # 修改按钮上的文字显示
    self.btn_1.clicked.connect(self.close) # 点击触发close事件
    

    当然你也可以自定义:

    self.btn_1.clicked.connect(self.closeEvent) # 点击触发close事件
    
    def closeEvent(self, event):
    	# 写自己的代码
        sys.exit(0)
    

    第二种方式就是采用键盘触发close事件关闭窗口。这里列举了分别按下ESC键和Enter回车键触发close窗口事件。

    import sys
    from PySide6.QtWidgets import QMainWindow, QApplication
    from PySide6 import QtGui
    from PySide6.QtCore import Qt
    
    from ui_main import Ui_MainWindow
    
    
    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)
            # 隐藏窗口边框
            self.setWindowFlags(Qt.FramelessWindowHint)
    
        def keyPressEvent(self, event: QtGui.QKeyEvent):
            key = event.key()
    
            if key == Qt.Key_Escape:
                self.close()
            elif key == Qt.Key_Enter or key == Qt.Key_Return:
                self.close()
    
    
        def mousePressEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.mouse_start_pt = event.globalPosition().toPoint()
                self.window_pos = self.frameGeometry().topLeft()
                self.drag = True
    
        def mouseMoveEvent(self, event: QtGui.QMouseEvent):
            if self.drag:
                distance = event.globalPosition().toPoint() - self.mouse_start_pt
                self.move(self.window_pos + distance)
    
        def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
            if event.button() == Qt.LeftButton:
                self.drag = False
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        win = MainWindow()
        win.show()
        app.exec()
    

    在这里插入图片描述

  • 相关阅读:
    nodejs毕业设计学生宿舍寝室管理系统
    漫谈广告机制设计 | 混排:广告与自然结果的交锋博弈(2)
    文件上传OSS实现
    信息学奥赛一本通:1171:大整数的因子
    Web3 DApp用户体验最佳实践
    Pro_06丨重心拐点与高低波出场
    LeetCode //C - 67. Add Binary
    day04_java基础
    【深入浅出设计模式--命令模式】
    【LeetCode热题100】--74.搜索二维矩阵
  • 原文地址:https://blog.csdn.net/qq_45062768/article/details/140964466