Python app 03 making video player using PYQT

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 TimeImportSYS fromPyQt4ImportQtgui, Qtcore fromPyqt4.phononImportPhononclassPolltimethread (qtcore.qthread):"""This thread works as a timer. """Update=qtcore.pyqtsignal ()def __init__(self, parent): Super (Polltimethread, self).__init__(parent)defRun (self): whileTrue:time.sleep (1)            ifself.isrunning ():#Emit SignalSelf.update.emit ()Else:                returnclassWindow (qtgui.qwidget):def __init__(self): Qtgui.qwidget.__init__(self)#MediaSelf.media =Phonon.mediaobject (self) self.media.stateChanged.connect (self.handlestatechanged) Self.video=phonon.videowidget (self) self.video.setMinimumSize (200, 200) Self.audio=Phonon.audiooutput (phonon.videocategory, self) phonon.createpath (Self.media, Self.audio) Phonon.createP Ath (Self.media, Self.video)#control buttonSelf.button = Qtgui.qpushbutton ('Select File', self) self.button.clicked.connect (Self.handlebutton)#For display of time lapseSelf.info =Qtgui.qlabel (self)#LayoutLayout =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-slot, for time lapseSelf.thread =Polltimethread (self) self.thread.update.connect (self.update)defUpdate (self):#Slotslapse = Self.media.currentTime ()/1000.0Self.info.setText ("%4.2f sec"%lapse)defStartplay (self):ifSelf.path:self.media.setCurrentSource (Phonon.mediasource (self.path))#Use a thread as a timerSelf.thread =Polltimethread (self) self.thread.update.connect (self.update) Self.thread.start () sel F.media.play ()defHandlebutton (self):ifSelf.media.state () = =Phonon.PlayingState:self.media.stop () self.thread.terminate ( )Else: Self.path=QtGui.QFileDialog.getOpenFileName (Self, Self.button.text ()) Self.startplay ()defhandlestatechanged (self, NewState, oldstate):ifNewState = =Phonon.PlayingState:self.button.setText ('Stop')        elif(NewState! = Phonon.loadingstate andnewstate!=phonon.bufferingstate): Self.button.setText ('Select File')            ifNewState = =Phonon.ErrorState:source=Self.media.currentSource (). FileName ()Print('error: Cannot play:', Source.tolocal8bit (). Data ())Print('%s'%self.media.errorString (). Tolocal8bit (). Data ())if __name__=='__main__': App=qtgui.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 = 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 =4, 1, 1, 35, 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:

classPolltimethread (qtcore.qthread):"""This thread works as a timer. """Update=qtcore.pyqtsignal ()def __init__(self, parent): Super (Polltimethread, self).__init__(parent)defRun (self): whileTrue:time.sleep (1)            ifself.isrunning ():#Emit SignalSelf.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

Python app 03 making video player using PYQT

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.