🚀🚀🚀 Pyside6实战教程专栏目录入口:点击跳转
目录
- 一、前期准备
- 二、鼠标触发事件
- 鼠标拖动窗口
一、前期准备
我们采用Pyside入门实战之四中通过QTDesigner创建的界面,具体由两个Label和一个Button组件构成(含背景),如下所示:
import sys
from PySide6.QtWidgets import QMainWindow, QApplicationfrom ui_main import Ui_MainWindowclass 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 Qtfrom ui_main import Ui_MainWindowclass 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()
鼠标拖动窗口
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 = Truedef mouseMoveEvent(self, event: QtGui.QMouseEvent):if self.drag:distance = event.globalPosition().toPoint() - self.mouse_start_ptself.move(self.window_pos + distance)def mouseReleaseEvent(self, event: QtGui.QMouseEvent):if event.button() == Qt.LeftButton:self.drag = False