[Python combat basics] How to create PyQt6 event objects in Python

Table of contents

1. The actual combat scene

2. Main points of knowledge

file read and write

Basic grammar

PyQt6

sys

Three, rookie combat


1. The actual combat scene

Practical scenario: How to create PyQt6 event objects in Python

2. Main points of knowledge

  • file read and write

  • Basic grammar

  • PyQt6

  • sys

Three, rookie combat

The event object is a Python object that contains a series of attributes describing the event, depending on the triggering event.

import sys
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QWidget, QApplication, QGridLayout, QLabel


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        grid = QGridLayout()

        x = 0
        y = 0

        self.text = f'x: {x},  y: {y}'

        self.label = QLabel(self.text, self)
        grid.addWidget(self.label, 0, 0, Qt.Alignment.AlignTop)

        self.setMouseTracking(True)
        self.setLayout(grid)

        self.setGeometry(300, 300, 450, 300)
        self.setWindowTitle('Event object')
        self.show()


    def mouseMoveEvent(self, e):

        x = int(e.position().x())
        y = int(e.position().y())

        text = f'x: {x},  y: {y}'
        self.label.setText(text)


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

In this example, in the label component, the coordinates of the mouse are displayed.

self.setMouseTracking(True)

Mouse tracking is disabled by default. When the mouse is moved, the component can only receive events when the mouse is pressed. Turn on mouse tracking, and you can also receive events by moving the mouse without pressing the mouse button.

def mouseMoveEvent(self, e):

    x = int(e.position().x())
    y = int(e.position().y())
    ...

e is the event object, which contains the data when the event was triggered. Through the  position().x() and  e.position().y() method, the coordinate value of the mouse can be obtained.

self.text = f'x: {x},  y: {y}'
self.label = QLabel(self.text, self)

Coordinate values ​​x and y are displayed in the  QLabel component.

Rookie combat, keep learning!  

Guess you like

Origin blog.csdn.net/qq_39816613/article/details/127122938