Python3 uses PyQt5 to create a simple canvas/tablet instance, and python3pyqt5

Source: Internet
Author: User

Python3 uses PyQt5 to create a simple canvas/tablet instance, and python3pyqt5

1. Preface

Version: Python3.6.1 + PyQt5

When writing a program, you need to use the canvas or tablet. You only need the simplest one. I thought it was everywhere on the Internet. After searching for the results for several days, I did not find the desired results.

The online qt program is either a non-python version (you need to know whether the differences between qt versions are huge or not the same language), which is too difficult to rewrite. Or the old PyQt4 program, many of which cannot run on PyQt5. Either it is a very complex program written by a great god. It is simply a built-in drawing version of Windows, and can only worship ~

As a result, I can only find the small part I need in a large number of codes, and then piece it together, constantly understand the code of the great god, and finally make such a simple canvas. Looking at this simple canvas, I burst into tears. Dozens of failed attempts in the middle caused numerous program crashes and almost gave up ......

2. Simple canvas 1.0

In simple drawing board 1.0, the function is to draw a line between a fixed point and a moving mouse.
:

If you press and hold the mouse, the line will also move. You can understand the running mechanism of PyQt5 from this simple program.

'''Simple canvas 1.0 function: draw a line between a fixed point and a moving mouse Author: PyLearn last modification date: ''' import sysfrom PyQt5.QtWidgets import (QApplication, QWidget) from PyQt5.QtGui import (QPainter, QPen) from PyQt5.QtCore import Qtclass Example (QWidget): def _ init _ (self): super (Example, self ). _ init _ () # resize: Set the width and height. move: Set the position self. resize (400,300) self. move (100,100) self. setWindowTitle ("simple canvas 1.0") # setMouseTracking is set to False. Otherwise, the mouse event self will be tracked if you do not press the mouse. setMouseTracking (False) # Set the x and y coordinates of the vertices in the two variables. pos_x = 20 self. pos_y = 20 def paintEvent (self, event): painter = QPainter () painter. begin (self) pen = QPen (Qt. black, 2, Qt. solidLine) painter. setPen (pen) # point (20, 20) to (self. pos_x, self. painter. drawLine (20, 20, self. pos_x, self. pos_y) painter. end () def mouseMoveEvent (self, event): ''' press and hold the mouse to move the event: update the values of pos_x and pos_y. Calling the update () function is equivalent to calling paintEvent () every time a function is updated (), the traces of paintEvent () previously called will be cleared '''self. pos_x = event. pos (). x () self. pos_y = event. pos (). y () self. update () if _ name _ = "_ main _": app = QApplication (sys. argv) pyqt_learn = Example () pyqt_learn.show () app.exe c _()

3. Simple canvas 2.0

From the running of the above simple drawing board 1.0 program, we can find that when you press and hold the mouse, the line will also move. How can we leave traces on the previous line instead of disappearing?

In simple canvas 2.0, you can use a list to save all the moving points. When you want to draw a line, traverse the list cyclically and draw the line between the point and the point in the list in sequence.

Effect:

'''Simple canvas 2.0 function: draw a line between a fixed point and a moving mouse, and keep the drawn line on the form Author: PyLearn last modification date: ''' import sysfrom PyQt5.QtWidgets import (QApplication, QWidget) from PyQt5.QtGui import (QPainter, QPen) from PyQt5.QtCore import Qtclass Example (QWidget): def _ init _ (self ): super (Example, self ). _ init _ () # resize: Set the width and height. move: Set the position self. resize (400,300) self. move (100,100) self. setWindowTitle ("simple canvas 2.0") # setMouseTracking is set to False. Otherwise, the mouse event self will be tracked if you do not press the mouse. setMouseTracking (False) ''' to keep the drawn lines on the form, you need a list to save all the moved points ''' self. pos_xy = [] def paintEvent (self, event): painter = QPainter () painter. begin (self) pen = QPen (Qt. black, 2, Qt. solidLine) painter. setPen (pen) # cyclically traverse self. for each vertex in pos_xy, draw the line between the vertex and the fixed point for pos_tmp in self. pos_xy: painter. drawLine (20, 20, pos_tmp [0], pos_tmp [1]) painter. end () def mouseMoveEvent (self, event): ''' press and hold the mouse to move the event: add the current vertex to the pos_xy list. Calling the update () function is equivalent to calling paintEvent () every time the function is updated (), the traces left by the paintEvent () called earlier will be cleared ''' # The intermediate variable pos_tmp to extract the current point pos_tmp = (event. pos (). x (), event. pos (). y () # Add pos_tmp to self. self in pos_xy. pos_xy.append (pos_tmp) self. update () if _ name _ = "_ main _": app = QApplication (sys. argv) pyqt_learn = Example () pyqt_learn.show () app.exe c _()

4. Simple canvas 3.0

Now, let's go to the topic. A simple drawing board 2.0 is just a line from the point where the mouse is located to a fixed point. How can we keep the track moving behind the mouse on the form?

This requires a list to store all the moving points, and draw a line between all the adjacent two points to intermittently link the mouse marks.
Effect:

Just draw the mouse movement track!

However, this also has some disadvantages. For example, write a 5 Review:



5 is not 5, 6 is not 6. This is because when the strokes are raised again, the figure above 5 is connected to the previously painted tail. Think about how to solve this problem?

'''Simple canvas 3.0 function: retain the trajectory moving after holding the mouse on the form Author: PyLearn last modification date: ''' import sysfrom PyQt5.QtWidgets import (QApplication, QWidget) from PyQt5.QtGui import (QPainter, QPen) from PyQt5.QtCore import Qtclass Example (QWidget): def _ init _ (self): super (Example, self ). _ init _ () # resize: Set the width and height. move: Set the position self. resize (400,300) self. move (100,100) self. setWindowTitle ("simple canvas 3.0") # setMouseTracking is set to False. Otherwise, the mouse event self will be tracked if you do not press the mouse. setMouseTracking (False) ''' to keep the track moving after holding the mouse down on the form, a list is required to save all the moved vertices ''' self. pos_xy = [] def paintEvent (self, event): painter = QPainter () painter. begin (self) pen = QPen (Qt. black, 2, Qt. solidLine) painter. setPen (pen) ''' first, judge whether there are at least two vertices in the pos_xy list. Then, assign the first vertex in pos_xy to point_start and use the intermediate variable pos_tmp to traverse the entire pos_xy list point_end = pos_tmp to draw between point_start and point_end. line point_start = point_end, by constantly drawing lines between two adjacent points, you can move the mouse over the '''if len (self. pos_xy)> 1: point_start = self. pos_xy [0] for pos_tmp in self. pos_xy: point_end = pos_tmp painter. drawLine (point_start [0], point_start [1], point_end [0], point_end [1]) point_start = point_end painter. end () def mouseMoveEvent (self, event): ''' press and hold the mouse to move the event: add the current vertex to the pos_xy list. Calling the update () function is equivalent to calling paintEvent () every time the function is updated (), the traces left by the paintEvent () called earlier will be cleared ''' # The intermediate variable pos_tmp to extract the current point pos_tmp = (event. pos (). x (), event. pos (). y () # Add pos_tmp to self. self in pos_xy. pos_xy.append (pos_tmp) self. update () if _ name _ = "_ main _": app = QApplication (sys. argv) pyqt_learn = Example () pyqt_learn.show () app.exe c _()

5. Simple canvas 4.0

There is a fatal problem in the simple canvas 3.0, that is, the continuous problem. For example, you need to write a three-digit number 123:


It's ugly, right?

There are many ways to solve this problem. I did not think deeply, so I used this troublesome method directly.

My solution is to add a breakpoint (-1,-1) to the list of all moved points when the mouse moves and then releases it ). Then, when you draw a line, you can determine whether it is a breakpoint. If it is a breakpoint, you can find a way to jump over and start to draw a line without interruption.

Effect:



The specific implementation code is as follows:

'''Simple canvas 4.0 function: Keep the track moving after holding the mouse on the form and solve the problem of continuity with the last trace during secondary painting. Author: PyLearn last modification date: ''' import sysfrom PyQt5.QtWidgets import (QApplication, QWidget) from PyQt5.QtGui import (QPainter, QPen) from PyQt5.QtCore import Qtclass Example (QWidget): def _ init _ (self ): super (Example, self ). _ init _ () # resize: Set the width and height. move: Set the position self. resize (400,300) self. move (100,100) self. setWindowTitle ("simple canvas 4.0") # setMouseTracking is set to False. Otherwise, the mouse event self will be tracked if you do not press the mouse. setMouseTracking (False) ''' to keep the track moving after holding the mouse down on the form, a list is required to save all the moved vertices ''' self. pos_xy = [] def paintEvent (self, event): painter = QPainter () painter. begin (self) pen = QPen (Qt. black, 2, Qt. solidLine) painter. setPen (pen) ''' first judge whether there are at least two vertices in the pos_xy list, and then assign the first vertex in pos_xy to point_start. Use the intermediate variable pos_tmp to traverse the entire pos_xy list point_end = pos_tmp to determine whether point_end is a breakpoint, if point_start is assigned a value to the breakpoint continue to determine whether point_start is a breakpoint, if point_start is assigned a value to point_end continue to draw a line between point_start and point_end, point_start = point_end, and draw lines between adjacent two points continuously, you will be able to move the cursor to the path ''' if len (self. pos_xy)> 1: point_start = self. pos_xy [0] for pos_tmp in self. pos_xy: point_end = pos_tmp if point_end = (-1,-1): point_start = (-1,-1) continue if point_start = (-1,-1 ): point_start = point_end continue painter. drawLine (point_start [0], point_start [1], point_end [0], point_end [1]) point_start = point_end painter. end () def mouseMoveEvent (self, event): ''' press and hold the mouse to move the event: add the current vertex to the pos_xy list. Calling the update () function is equivalent to calling paintEvent () every time the function is updated (), the traces left by the paintEvent () called earlier will be cleared ''' # The intermediate variable pos_tmp to extract the current point pos_tmp = (event. pos (). x (), event. pos (). y () # Add pos_tmp to self. self in pos_xy. pos_xy.append (pos_tmp) self. update () def mouseReleaseEvent (self, event): ''' re-press and hold the mouse to release the event. After each release, add a breakpoint (-1,-1) to the pos_xy list) then, when painting, you can determine whether it is a breakpoint. If it is a breakpoint, it will jump over, not with the previous continuous ''' pos_test = (-1,-1) self. pos_xy.append (pos_test) self. update () if _ name _ = "_ main _": app = QApplication (sys. argv) pyqt_learn = Example () pyqt_learn.show () app.exe c _()

So far, we have finally completed the implementation of a simple canvas program!

In addition, if you encounter any problems when using this code, please feel free to give me feedback.

The above Python3 uses PyQt5 to create a simple canvas/tablet instance, which is all the content that I have shared with you. I hope to give you a reference and support for the help house.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.