Want to write GUI with PyQt5, but the PYQT5 resources on the Internet are too few, find an English, translate, and learn PYQT5 students to encourage!
(All code in this series is tested through the Windows7 64-bit []/python 3.4.3 32bit/pyqt GPL v5.5 for Python v3.4 (x32)/eric6-6.0.8.)
Original address: http://zetcode.com/gui/pyqt5/
================================================================================ First PYQT5 program
In this part, we learn some basic functions.
a simple example
This is a simple example, it shows a small window. We can do a lot of things with this window, we can resize it, maximize it, or minimize it. This requires a lot of code. But someone has already written this feature. Because it repeats itself in most applications, there is no need to write it over and over again. PYQT5 is an advanced toolset. If we think of it as a low-level toolset, the following code example might have hundreds of lines.
Import sys
from pyqt5.qtwidgets import qapplication, qwidget
if __name__ = = ' __main__ ':
app = Qapplication ( SYS.ARGV)
w = qwidget ()
w.resize (
w.move)
w.setwindowtitle (' simple ')
W.show ()
sys.exit (App.exec_ ())
The above code displays a small window on the screen.
Import sys
from pyqt5.qtwidgets import qapplication, Qwidget
Here are the necessary imports. The basic windows are set in the Pyqt5.qtwidgets module.
App = Qapplication (SYS.ARGV)
Each PYQT5 application must create an Application object. The SYS.ARGV parameter is a list of arguments from the command line. Python scripts run from the shell. This is one way we can control how our scripts run.
W = Qwidget ()
The Qwidget window is the base class for all user interface objects in PYQT5. We used the Qwidget default constructor. The default constructor does not have a parent class. A window without a parent class is called a Windows.
W.resize (250, 150)
The resize () method adjusts the size of the window. is adjusted to 250 like pixels and 150 pixel high.
W.move (300, 300)
The move () method moves the window to the screen coordinates x=300, y=300 position.
W.setwindowtitle (' simple ')
Here we set the title of the window. The title will be displayed on the title bar.
W.show ()
The show () method displays the window on the screen. A window is first created in memory and then displayed on the screen.
Sys.exit (App.exec_ ())
Finally, we go into the main loop of the application. Event handling starts here. The main loop receives events from the window system and assigns them to the application window. If we call the exit () method or the main window is destroyed, the main loop ends. Sys.exit () method to ensure a complete exit. Environment variables are notified of how the application ends.
The Exec_ () method has an underscore. This is because EXEC is a keyword in python. Therefore, replace with EXEC_ ().
Photo: simple Example
an application icon
An application icon is a small image to display in the upper-left corner of the title bar. In the following example we will demonstrate in PyQt5, and we will introduce a new approach.
Import sys
from pyqt5.qtwidgets import qapplication, qwidget from
Pyqt5.qtgui import Qicon
class Example ( Qwidget):
def __init__ (self):
super (). __init__ ()
Self.initui ()
def initui (self):
Self.setgeometry (Self.setwindowtitle) Self.setwindowicon ('
Icon ') (
qicon (' web.png '))
self.show ()
if __name__ = = ' __main__ ':
app = Qapplication (SYS.ARGV)
ex = Example ()
sys.exit (App.exec_ ())
The previous example was written in a traditional procedural style. The Python programming language supports both procedural and object-oriented programming styles. Programming in PYQT5 means OOP.
Class Example (Qwidget):
def __init__ (self):
super (). __init__ ()
...
The important thing in object-oriented programming is classes, data, and methods. Here we create a new class called Example. The example class is inherited from the Qwidget class. This means that we can call two constructors: The second. Super () method for the first and inheriting classes of the example class returns the parent object of the example class, and we call its constructor. The __init__ () method is a method of construction in the Python language.
Self.initui ()
The creation of the GUI is delegated to the Initui () method.
Self.setgeometry (Self.setwindowtitle) Self.setwindowicon ('
Icon ') (
qicon (' web.png '))
These three methods are inherited from the Qwidget class. The Setgeometry () method does two things: position the window on the screen and set its size. The first two arguments are the x and Y axes of the window. The third argument is the width of the window, and the fourth parameter is the height of the window. Actually, it's putting resize The two methods () and move () are merged into one method. The next method is to set the application's icon. First we want to create a Qicon object, Qicon receive the path to our icon and display it: The path here is the relative path-relative to the location of your source code, or the absolute path ).
if __name__ = = ' __main__ ':
app = Qapplication (SYS.ARGV)
ex = Example ()
sys.exit (App.exec_ ())
Application and example objects are created. The main loop begins.
Images: Icons
display a hint message
We can provide suspension help information for any of our forms.
Import SYS from
pyqt5.qtwidgets import (Qwidget, Qtooltip,
Qpushbutton, qapplication) from
Pyqt5.qtgui Import Qfont
class Example (qwidget):
def __init__ (self):
super (). __init__ ()
Self.initui ()
def Initui (self):
Qtooltip.setfont (Qfont (' Sansserif '))
Self.settooltip (' This is a <b>qwidget</b > Widget ')
btn = Qpushbutton (' Button ', self)
btn.settooltip (' This is a <b>QPushButton</b> Widget ')
btn.resize (Btn.sizehint ()) (
btn.move)
self.setgeometry
(+) Self.setwindowtitle (' tooltips ')
self.show ()
if __name__ = = ' __main__ ':
app = Qapplication (SYS.ARGV)
ex = Example ()
sys.exit (App.exec_ ())
In this example, we display a hint for two PyQt5 forms.
Qtooltip.setfont (Qfont (' Sansserif ', 10))
This static method sets a font used to draw the hint information. We used a 10-pixel sansserif font.
Self.settooltip (' This is a <b>QWidget</b> widget ')
To create a hint, we call the SetToolTip () method. We can format it directly with a multiple format file.
BTN = Qpushbutton (' Button ', self)
btn.settooltip (' This is a <b>QPushButton</b> widget ')
We create a click button and give it a hint message.
Btn.resize (Btn.sizehint ())
Btn.move (50, 50)
This is used to define the size of the button and the. Sizehint () method that gives the button a recommended size.
Picture: Hint info close a window
The most obvious closing of a window is to click on the title bar on the X. In the next example, we show how to programmatically close our windows. We'll touch a little bit of signal and slot.
Here is a Qpushbutton part builder, which we'll use in the example.
Qpushbutton (string text, qwidget parent = None)
The text argument is what is displayed on the button. Parent is the part where we place the button. In our case, parent is a qwidget. Parts of an application will form a hierarchy. At this level, Most of the parts have their parent class. A part that has no parent is the topmost window.
Import SYS from
pyqt5.qtwidgets import Qwidget, Qpushbutton, qapplication from
pyqt5.qtcore Import Qcoreapplication
class Example (qwidget):
def __init__ (self):
super (). __init__ ()
Self.initui ()
def initui (self):
qbtn = Qpushbutton (' Quit ', self)
qbtn.clicked.connect (Qcoreapplication.instance (). Quit)
qbtn.resize (Qbtn.sizehint ()) Qbtn.move (())
self.setgeometry
(in) Self.setwindowtitle (' Quit button ')
self.show ()
if __name__ = = ' __main__ ':
app = Qapplication (sys.argv
ex = Example ()
sys.exit (App.exec_ ())
In this example, we create an exit button. When you click this button, the application terminates.
From Pyqt5.qtcore import qcoreapplication
We need objects from the Qtcore module.
QBTN = Qpushbutton (' Quit ', self)
We create a button. The button is an instance of the Qpushbutton class. The first parameter of the constructor is the label of the button, and the second parameter is the parent part class. The parent part is a example part, inherited from Qwidget.
Qbtn.clicked.connect (Qcoreapplication.instance (). Quit)
The event handling system in PYQT5 is constructed with signal and slot mechanism. If we click on the button, the click Signal will be emitted. The slot can be a qt slot or any Python callable. The qcoreapplication contains the main event loops; It handles and dispatches all events. Instance () method gives us its current instance. Note that the qcoreapplication was created with Qapplication. Click on the information to be connected to the Quit () method, It terminates the program. The communication is done between the sender and receiver. The sender here is the click button and the receiver is the program object.
Picture: Exit button message box
By default, if we click on the title bar, the X,qwidget will be closed. Sometimes we want to modify a default. For example, if we have an open file in the editor, we make some changes. We would like to display a message box to confirm the operation.
Import sys
from pyqt5.qtwidgets import Qwidget, Qmessagebox, Qapplication
class Example (qwidget):
def __ Init__ (self):
super (). __init__ ()
Self.initui ()
def initui (self):
self.setgeometry (300, 300, 250,
self.setwindowtitle (' message box ')
self.show ()
def closeevent (Self, event):
reply = Qmessagebox.question (self, ' message ',
"Are and sure to quit?", Qmessagebox.yes |
Qmessagebox.no, qmessagebox.no)
if reply = = Qmessagebox.yes:
event.accept ()
else:
event.ignore ()
if __name__ = = ' __main__ ':
app = Qapplication (SYS.ARGV)
ex = Example () sys.exit (
app.exec_ ())
If we close a qwidget,qcloseevent will be generated. To modify the part behavior, we need to implement the Closeevent () event handler again.
Reply = Qmessagebox.question (self, ' message ',
"Are-sure to quit?", Qmessagebox.yes |
Qmessagebox.no, qmessagebox.no)
We display a message box with two buttons: Yes and No. The first string is displayed on the title bar. The second string is the message text of the dialog box. The third parameter specifies the button that appears in the dialog box. The last parameter is the default button. It is the original keyboard focus. The return value is stored in the reply variable.
if reply = = QtGui.QMessageBox.Yes:
event.accept ()
Else:
Here we test the return value. If we click the Yes button, we accept the event, which causes the part to close and terminate the program. Otherwise, the shutdown event is ignored.
Picture: message box put the window in the middle of the screen
The following script shows how we and a window are placed in the middle of the desktop.
Import sys
from pyqt5.qtwidgets import Qwidget, Qdesktopwidget, Qapplication
class Example (qwidget):
def _ _init__ (self):
super (). __init__ ()
Self.initui ()
def initui (self):
self.resize (in
) Self.center ()
self.setwindowtitle (' center ')
Self.show ()
def Center (self):
QR = Self.framegeometry ()
CP = Qdesktopwidget (). Availablegeometry (). Center ()
Qr.movecenter (CP)
Self.move (Qr.topleft ())
if __name__ = = ' __main__ ':
app = Qapplication (SYS.ARGV)
ex = Example ()
Sys.exit (App.exec_ ())
The Qtgui.qdesktopwidget class acts as a user's desktop information, including screen size.
Self.center ()
This code puts the window in the middle by invoking the custom Center () method.
qr = Self.framegeometry ()
We get a rectangular description of the main form through this. This contains any window frames.
CP = Qdesktopwidget (). Availablegeometry (). Center ()
We calculate the screen resolution of the monitor. Through this, we'll get the center point.
Qr.movecenter (CP)
Our rectangle already has its width and height. Now we set the center point of the rectangle to the center of the screen. The size of the rectangle has not been modified.
Self.move (Qr.topleft ())
We move the upper-left corner of the program window to the upper-left corner of the QR rectangle, so the window is placed in the center of the screen.
Photo: Positive Center