Thursday, April 26, 2018

Python Qt5 - menu example.

This simple tutorial is about PyQt5 and menu window example.
I have a similar example with Qt4 on this blog.
The main reason for this tutorial comes from the idea of simplicity and reuse the source code from PyQt4 and PyQt5.
I do not know if there are significant changes to the Qt5 base IU. However, it is good to check on the official pages. Let's look at the example with comments specific to source code lines:
# -*- coding: utf-8 -*-
Created on Thu Apr 26 17:20:02 2018

@author: catafest
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QDesktopWidget
from PyQt5.QtGui import QIcon

class Example(QMainWindow):
    #init the example class to draw the window application    
    def __init__(self):
    #create the def center to select the center of the screen         
    def center(self):
        # geometry of the main window
        qr = self.frameGeometry()
        # center point of screen
        cp = QDesktopWidget().availableGeometry().center()
        # move rectangle's center point to screen's center point
        # top left of rectangle becomes top left of window centering it
    #create the init UI to draw the application
    def initUI(self):               
        #create the action for the exit application with shortcut and icon
        #you can add new action for File menu and any actions you need
        exitAct = QAction(QIcon('exit.png'), '&Exit', self)        
        exitAct.setStatusTip('Exit application')
        #create the status bar for menu 
        #create the menu with the text File , add the exit action 
        #you can add many items on menu with actions for each item
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        #resize the window application 
        self.resize(640, 480)
        #draw on center of the screen
        #add title on windows application 
        self.setWindowTitle('Simple menu')
        #show the application
        #close the UI class
if __name__ == '__main__':
    #create the application 
    app = QApplication(sys.argv)
    #use the UI with new  class
    ex = Example()
    #run the UI 
The result of this code is this:

No comments:

Post a Comment