Python

Hello World using PyQt

Version 3

Q How do I specify an icon for the dialog?

Q How do I organise the layout of a dialog?

Q How do I show a menu on a dialog?

Q How do I specify an icon for a menu?

A Here's a small Python program that uses the PyQt library. It shows a small, resizable, dialog …

Python Implementation

The Hello World 3 example borrows from Python articles and examples you can find on the Internet. It adds the MicroStation requirements for a dialog to work harmoniously as a Python app.

This example uses the PyQt user interface (abbreviated to UX or UI). PyQt terms its UX objects widgets. A widget is part of a window or dialog: a window or dialog usually contains several widgets. In this example we use QWindow, QMenu, QLabel and other widgets.

Dialog Layout

This app adds a menu bar to the dialog, by calling QMainWindow.menuBar(). The menu is placed automatically at the top of the dialog. The dialog uses a QGridLayout. The text in that grid layout is displayed by QLabel widgets.

Menu Actions

The app calls menuBar.addMenu(), once for the File menu and again for Help menu. Beneath the menu bar, each menu contains items, in this example the File|Exit and Help|Documentation sub-menus. When you choose a menu item, the PyQt menu triggers an action. The File|Exit menu triggers the exitCall(), which calls QWindow.close() to exit the app …

Class Inheritance

This example builds on the first Hello World and second Hello World 2 examples. It uses class inheritance by providing a main window base class MainWindowBase, which is defined in file la_solutions_qt_widgets.py. That base class performs some actions that are required by any QMainWindow. Those actions include that windows messages are passed to MicroStation, so that the Python application doesn't make MicroStation unresponsive.

The base class sets the main window caption …

class MainWindow(la_widgets.MainWindowBase):
    # Initialize the main window class
    def __init__(self):
        # Call the parent class's constructor to initialize the main window
        super().__init__("MicroStation Python")

It sets the main window's icon, which in this example is a smiley face …

Smiley
	iconPath = la_utilities.getFileFromScriptFolder ('smiley-icon.png')
	self.setWindowIcon(QIcon(iconPath))

There are several Python utility modules …

The Python source code of Hello World V3 is available for download. The ZIP package includes several files …

The app file is HelloWorld3.py. It uses several Python library files …

Download PyQt-HelloWorld3.zip

Unpack the ZIP file and copy the Python files into a folder that MicroStation knows about. Copy the images files into the same folder.

Python Manager

Use MicroStation's Python Manager to find and execute the script.

Questions

Post questions about MicroStation Python programming to the MicroStation Programming Forum.