PyQt5学习记录(一):Event object

之前在上看到一系列的文章链球选手,介绍了关于PyQt5的使用,跟着学到了不少东西,在此感谢.更新中断了,发现是http://zetcode.com/翻译下来的,所以直接去这学习了.非常感谢!

Event object is a Python object that contains a number of attributesdescribing the event. Event object is specific to the generated eventtype.
[译文]事件对象是一个Python对象,包含了一些attributesdescribing事件。事件对象是特定生成的事件类型。

下面是源码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/10/20 下午2:42
# @Author  : hukezhu
# @Site    : 
# @File    : 1020-05-Event object.py
# @Software: PyCharm

"""

    在这个例子中,我们在一个标签控件中显示了鼠标指针的坐标x和y。

"""

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


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        
        grid = QGridLayout()
        grid.setSpacing(10)

        x = 0
        y = 0

        self.text = "x: {0},  y: {1}".format(x, y)

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

        self.setMouseTracking(True)

        self.setLayout(grid)

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

    def mouseMoveEvent(self, e):
        x = e.x()
        y = e.y()

        text = "x: {0},  y: {1}".format(x, y)
        self.label.setText(text)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

关键代码解读

  1. 在这个例子中,我们在label控件上显示了鼠标移动的x,y坐标.
self.text = "x: {0},  y: {1}".format(x, y)

self.label = QLabel(self.text, self)
  1. Mouse tracking属性默认是关闭的.

Mouse tracking is disabled by default, so the widget only receives mouse move events when at least one mouse button is pressed while the mouse is being moved.If mouse tracking is enabled, the widget receives mouse move events even if no buttons are pressed.

self.setMouseTracking(True)

The "e" is the event object; it contains data about the event that was triggered; in our case, a mouse move event. With the x() and y() methods we determine the x and y coordinates of the mouse pointer. We build the string and set it to the label widget.

def mouseMoveEvent(self, e):
    
    x = e.x()
    y = e.y()
    
    text = "x: {0},  y: {1}".format(x, y)
    self.label.setText(text)

运行效果图:

PyQt5学习记录(一):Event object_第1张图片
QQ20171020-160553.png

你可能感兴趣的:(PyQt5学习记录(一):Event object)