Thursday, November 29, 2018

Catalin George Festila: Python Qt5 - submenu example.

Using my old example I will create a submenu with PyQt5.
First, you need to know the submenu works like the menu.
Let's see the result:

The source code is very simple:
# -*- coding: utf-8 -*-
"""
@author: catafest
"""
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QDesktopWidget, QMenu
from PyQt5.QtGui import QIcon

class Example(QMainWindow):
#init the example class to draw the window application
def __init__(self):
super().__init__()
self.initUI()
#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
qr.moveCenter(cp)
# top left of rectangle becomes top left of window centering it
self.move(qr.topLeft())
#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.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(qApp.quit)
#create the status bar for menu
self.statusBar()
#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')
fileMenu.addAction(exitAct)

# add submenu to menu
submenu = QMenu('Submenu',self)

# some dummy actions
submenu.addAction('Submenu 1')
submenu.addAction('Submenu 2')

# add to the top menu
menubar.addMenu(submenu)
#resize the window application
self.resize(640, 480)
#draw on center of the screen
self.center()
#add title on windows application
self.setWindowTitle('Simple menu')
#show the application
self.show()
#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
sys.exit(app.exec_())


from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...