PYQT Making video Player

Source: Internet
Author: User
Tags emit

Vamei Source: Http://www.cnblogs.com/vamei prohibited any form of reprint.

A recent study of Python's two GUI packages, Tkinter and PYQT. The bottom layer of the two GUI packages is TCL/TK and QT respectively. By contrast, I think PYQT is more convenient to use and more versatile. This article uses PYQT to implement a video player, and to illustrate the basic usage of PYQT.

Video player

Let's put the finished code out first. The code is based on Python 3.5:

Import timeimport sysfrom PyQt4 import Qtgui, qtcorefrom pyqt4.phonon import phononclass polltimethread (qtcore.qthread):    "" This thread works as a timer.    "" "Update = Qtcore.pyqtsignal () def __init__ (self, parent): Super (Polltimethread, self). __init__ (parent)                def run (self): while True:time.sleep (1) if self.isrunning (): # Emit signal        Self.update.emit () Else:returnclass Window (qtgui.qwidget): def __init__ (self): Qtgui.qwidget.__init__ (self) # media Self.media = Phonon.mediaobject (self) self.media.stateCha Nged.connect (self.handlestatechanged) Self.video = Phonon.videowidget (self) self.video.setMinimumSize (200, 2        XX) Self.audio = Phonon.audiooutput (phonon.videocategory, self) phonon.createpath (Self.media, Self.audio) Phonon.createpath (Self.media, Self.video) # control button Self.button = QTGUI.QPUSHBUtton (' Select File ', self) Self.button.clicked.connect (Self.handlebutton) # for display of time lapse self.i  NFO = Qtgui.qlabel (self) # layout layout = Qtgui.qgridlayout (self) layout.addwidget (Self.video, 1, 1, 3, 3) Layout.addwidget (Self.info, 4, 1, 1, 3) layout.addwidget (Self.button, 5, 1, 1, 3) # Signal-slo T, for-time lapse self.thread = Polltimethread (self) self.thread.update.connect (self.update) def update (s ELF): # slot lapse = Self.media.currentTime ()/1000.0 self.info.setText ("%4.2f sec"% lapse) def star  Tplay (self): if Self.path:self.media.setCurrentSource (Phonon.mediasource (Self.path)) # Use a            Thread as a timer Self.thread = Polltimethread (self) self.thread.update.connect (self.update) Self.thread.start () Self.media.play () def Handlebutton (self): if self.media.state () = = phonon.pl Ayingstate:sElf.media.stop () self.thread.terminate () Else:self.path = QtGui.QFileDialog.getOpenFileName ( Self, Self.button.text ()) Self.startplay () def handlestatechanged (self, NewState, oldstate): if Newst              ate = = Phonon.PlayingState:self.button.setText (' Stop ') elif (newstate! = Phonon.loadingstate and NewState! = phonon.bufferingstate): Self.button.setText (' select File ') if newstate = = Phonon.errorstat E:source = Self.media.currentSource (). FileName () print (' ERROR: Cannot play: ', Source.tolocal8bit (). da TA ()) print ('%s '% self.media.errorString (). Tolocal8bit (). Data ()) if __name__ = = ' __main__ ': app = QTG Ui. Qapplication (SYS.ARGV) app.setapplicationname (' Video playback ') window = window () window.show () Sys.exit (App.exec_ ())

The code implements an application with a GUI window to play the video file. Video playback utilizes the phonon module in the PYQT. In addition, there is a process that sends a signal every second. The window updates the video playback time after the signal is received. The effect of this application is as follows:

Test run Environment for Mac OSX El Capitan.

View section

After writing this code, I found that this code is simple, but involves a few important mechanisms, you can use PYQT exercises. The following is a brief description of the code, first of all the main program section:

App = Qtgui.qapplication (sys.argv) ... window = window () window.show () Sys.exit (App.exec_ ())

In the PYQT program, Qapplication is the topmost object that refers to the entire GUI application. We created an Application object at the beginning of the program and then called EXEC_ () at the end of the program to run the application. Sys.exit () is used to require the application's main loop to exit cleanly after the end of the program. The beginning and end of the PYQT program are similar fixed routines. The key is the Qwidget object that is defined in the meantime.

Our custom window class inherits from Qwidget. In fact, Qwidget is the base class for all user interface objects and does not refer to just one window. tables, input boxes, and buttons are inherited from Qwidget. In a Window object, we also combine objects such as Qpushbutton and Qlabel, representing a button and a text box, respectively. They are arranged in a qgridlayout way, in the interface of the window, which is the following part of the code:

# layoutlayout = Qtgui.qgridlayout (self) ... layout.addwidget (Self.info, 4, 1, 1, 3) layout.addwidget (Self.button, 5, 1, 1, 3)

Qgridlayout divides the interface into meshes and attaches a view object to a specific grid location. For example, AddWidget () (Self.info, 4, 1, 1, 3) indicates that a text box object is placed in the position of the 4th row and 1th column. The text box will occupy 1 rows vertically and occupy 3 columns horizontally. In this way, the position relationship of the upper and lower views is determined by the layout. In addition to the layout of the net format, PYQT also supports other forms of layout, such as horizontal stacking, vertical stacking, etc., can be further understood.

In addition to QWIDGET,PYQT, a common dialog box is provided, such as:

Self.path = QtGui.QFileDialog.getOpenFileName (self, Self.button.text ())

The Qfiledialog dialog box here is used to select the file. The dialog box accesses the path to the selected file. In addition to file selection, the dialog box also has a confirmation dialog, a file input dialog, and a color dialog box. These dialogs implement a number of common GUI input functions. By using these dialogs, you can reduce the amount of work the programmer is developing from scratch.

Multithreading

The main thread of the GUI interface is usually left to the application master loop. Much of the other work is done through other threads. PYQT multithreaded programming is simple, only need to rewrite the Qthread run () method, you can:

Class Polltimethread (Qtcore.qthread):    def __init__ (self, parent):        super (Polltimethread, self). __init__ ( Parent)    def run (self):        ...

Once the thread is created, it is only necessary to call the start () method to run:

Self.thread = Polltimethread ()
... self.thread.start () # start thread
... self.thread.terminate () # terminating thread

Signal and slot

The GUI often uses asynchronous processing. For example, click on a button and invoke the corresponding callback function. QT's "Signal and Groove" (Signal-slot) mechanism is designed to solve asynchronous processing problems. We created the signal in the thread and signaled through the emit () method:

Class Polltimethread (Qtcore.qthread): "" "This    thread works as a timer.    " " Update = Qtcore.pyqtsignal ()    def __init__ (self, parent):        super (Polltimethread, self). __init__ (parent)    def run (self): while        True:            time.sleep (1)            if self.isrunning ():                # Emit signal                Self.update.emit ( )            Else:                return

With the signal, we can connect the signal to a "slot", which is actually the callback function corresponding to the signal:

Self.thread.update.connect (Self.update)

Each time the signal is emitted, the "slot" is called. In this example, the video playback time is updated. The "Signal and groove" in Qt is a universal mechanism. Some of the settings, such as buttons, preset "click" Such a signal, can directly correspond to the "slot." As in the code:

Self.button.clicked.connect (Self.handlebutton)

In addition, phonon is a very useful multimedia module, the use of the method is very simple, you can refer to the code itself, here no longer repeat.

Welcome to the Python quick tutorial

PYQT Making video Player

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.