PyQt5 easy to get started Guide 02, simple picture Display program

Source: Internet
Author: User
Tags documentation python decorator
a simple example

Here is a simple picture display program written in PYQT5.

The picture display program consists of a qlabel and Qpushbutton, when the button is clicked, a File selection dialog box pops up, allowing the user to select the appropriate picture file. The program will display the user's selected picture when the user presses the confirmation.
Startup script

main.py still acts as a startup script for this program.

Import SYS from
pyqt5.qtwidgets import qapplication from
dumbdialog import Dumbdialog   

The above code imports the necessary Pyqt5 class, completes the script to start. Among them, we made some minor changes to the Dumbdialog in the previous section. Instead of writing it in main.py, it is written separately in a script file called dumbdialog.py, which is then imported into the class by the code above. The next code:

if __name__ = = "__main__":      
    app = Qapplication (sys.argv)    #创建QApplication类的实例
    dia = Dumbdialog ()              # Create an instance of the Dumbdialog class
    dia.show ()                      #显示程序主窗口
    app.exec_ ()                     #开启事件主循环

If you have ever learned QT students, will not feel that the above code looks very familiar. Yes, PYQT and C + + qt, except for a little bit different in detail, all the other routines are similar. Most of the class's properties and methods do not change anything. In addition to a few key areas, other parts can be fully referenced in QT's C + + documentation. The main window of the program

The Dumbdialog class in dumbdialog.py is the main window for the program, and a Qlabel is responsible for displaying the information and pictures and a Qpushbutton for the pop-up file dialog box, which is displayed by Qlabel after the user chooses the appropriate picture.
The first is the definition of the class:

Class Dumbdialog (Qdialog):

The Qdialog class in parentheses indicates that this class is inherited from Qdialog, this is a Python object-oriented basic knowledge, do not understand the students can access the relevant information, personally think this is relatively simple, here will not repeat.
Then there is the constructor for this class:

def __init__ (self,  parent = None): 
        super (Dumbdialog,  Self). __init__ (parent)
        Self._title = "Image_ Loader "#设置类实例成员_title, whose value is the" image_laoder "self._diawidth = #设置实例成员_diawidth of the string, which is
        the value of the
        self._ Diaheight = 450 
        self.setwindowtitle (self._title) #设置窗口标题
        self.setminimumheight (self._diaheight) #设置窗口最小的大小
        self.setminimumwidth (self._diawidth)
        Self.imageview = Qlabel ("Add a image file") #得到一个QLabel的实例, and save it in the member ImageView, responsible for displaying messages and pictures
        self.imageView.setAlignment (qt.aligncenter) #设置QLabel居中显示
        Self.btn_open = Qpushbutton ("open") #实例化一个名为 "open" button and save it in class member Btn_open to get the path to the picture and display it in Qlabel
        self.btn_ Open.clicked.connect (self.on_btn_open_clicked) #pyqt5中信号与槽的连接
        self.vlayout = qvboxlayout ()
        Self.vlayout.addWidget (Self.imageview)
        self.vlayout.addWidget (self.btn_open)
        self.setlayout ( Self.vlayout)

We can see in the constructor that the code associated with the signal and slot connection is:

Self.widget_name.signal_name.connect (Self.slot_name)

The above code is represented in the PYQT4 in the following way:

Self.connect (Self.widget_name, SIGNAL ("Signal_name (args)"), Self.slot_name)

If the students have previously learned the C + + version of QT, it is easy to find that in the pyqt4 of the signal and slot connection and in C + + signal and groove connection is the most similar, but compared to pyqt5 in the new method this method is slightly troublesome, jumbled. slot Function

In Pyqt5, the number of slot functions is typically modified by the Python adorner @pyqtslot (TypeName). For example, the slot function is expressed as:

@pyqtSlot (BOOL)
def on_btn_open_clicked (self, checked):
    self.filename = Qfiledialog.getopenfilename (self, " OpenFile ",". ", 
            " Image Files (*.jpg *.jpeg *.png) ") [0]
        If Len (self.filename):
            self.image = QImage ( Self.filename)
            Self.imageView.setPixmap (Qpixmap.fromimage (self.image))
            self.resize (Self.image.width (), Self.image.height ())

By looking through the QT documentation, we can see that the clicked signal is a parameter with a bool, so we need to declare it in the adorner pyqtslot, that is, bool. Then, the second parameter of the slot function, "checked", is the specific value of this bool parameter. For the Python decorator is not very understanding of the students can go to the relevant information, this person is still relatively difficult to understand. Students can spend a little more time on this.
This slot function to do the work is very simple, after the user presses the button to pop up a file dialog box, the user selects the picture file after the file name stored in the Self.filename. A Qimage instance is then created with this specific file path to prepare for the use of the Qpixmap.fromimage method. This static method is then used to generate a Qpixmap instance, after which you can set the picture through the Qlabel setpixmap. The whole process is very simple and understandable. If you have questions about the above process, you can consult Qt's documentation. Summary

So far, this simple example has been analyzed. Students can download the project's source code for analysis and study in Https://git.oschina.net/linuxlike/PyQtJianYiRuMenZhiNan.
(This article is my personal analysis summary of the results, it is inevitable that there are deficiencies and errors in the place, if you see, please give comments on the relevant issues, to communicate.) )

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.