Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hardware and software Environment

  • Windows 10 64bit
  • Anaconda3 with python 3.7
  • PyQt5

preface

This article will implement the running light effect using the QTimeLine class, which is often used to control the animation timeline. Here we take the control QLabel as an example, to achieve text from left to right and right to left scrolling, first to see the final effect

The sample code

Look directly at the code, comments are written in the code

import sys from PyQt5.QtCore import QTimeLine from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QHBoxLayout, QVBoxLayout class Marquee(QWidget): def __init__(self): Super (Marquee, self).__init__() self.setwindowTitle ("PyQt5 ") self.resize(600, 600) self.label = QLabel(' Hello, I am a horselight! Welcome to my website: https://xugaoxiang.com ', self) # self.label. Move (-100, 280) # 10000 Timeline = QTimeLine(10000, self) # The faster the change of the self. The timeline. SetFrameRange (0, 500) # binding frameChanged signal to the groove function slot_frame_changed self. The timeline. FrameChanged. Connect (self. Slot_frame_changed) # set cycles, 0 means unlimited times self. The timeline. SetLoopCount (0) # start timeline, QTimeLine has three states, NotRunning, Running, and Paused, StateChanged self.timeline. Start () # create 2 buttons Self. forward_btn = QPushButton(' left to right ', self) self.backward_btn = QPushButton(' right to left ', self) Self.forward_btn. move(150, 100) self.backward_btn.move(350, 100) self.backward_btn.move(350, 100) 40) # Handle 2 clicks on self.forward_btn.clicked. Connect (lambda: self.slot_direction_changed(self.forward_btn)) self.backward_btn.clicked.connect( lambda: self.slot_direction_changed(self.backward_btn)) def slot_frame_changed(self, frame): Self.label. Move (-100 + frame, 280) def slot_direction_changed(self, BTN): self.label. Move (-100 + frame, 280) def slot_direction_changed(self, BTN): If BTN = = self. Forward_btn: # set timeline animation, from left to right, this is the default of the self. The timeline. The setDirection (QTimeLine. Forward) else: # set the timeline animation, self from right to left. The timeline. The setDirection (QTimeLine. Backward) if __name__ = = "__main__ ': app = QApplication(sys.argv) Marquee = Marquee() Marquee.show() sys.exit(app.exec_())Copy the code

Execute the above code to get the above effect

Download the source code

Github.com/xugaoxiang/…

PyQt5 series tutorials

For more PyQt5 tutorials, please go

Xugaoxiang.com/category/py…