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)

运行效果图:

QQ20171020-160553.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天买了一个可以无线链接的键盘感觉真好用。啊哈哈哈哈。以后就可以努力为大家敲字啦!
    小德肋撒阅读 164评论 0 0
  • 随着知识的积累,很多原来无法解释的事情,慢慢的可以用现学的储备理解清楚了。比如,就身边的人来讲。两个人,是发小,从...
    子轩哥哥阅读 252评论 0 0
  • 程一,你好。 我曾问过,为什么叫一,你还有弟弟妹妹叫程二程三吗?你答没有,你是独生子,是你爸妈省事取名一。...
    李小药阅读 420评论 2 3