PyQt4: Displaying Windows

While coding in PyQt, one should be little familiar with both the python language and Qt Gui programming.

How to write a minimal skeleton code:
First we have to add the following line to the script to avoid writing python for executing each script 😛
#!/usr/bin/python

Thereafter all the necessary modules will have to be imported. sys is needed to initialise the QApplication. QApplication is a kind of parent application in which all the GUI components work. According to Qt documentation-

“The QApplication class manages the GUI application’s control flow and main settings. It contains the main event loop, where all events from the window system and other sources are processed and dispatched. It also handles the application’s initialization and finalization, and provides session management. It also handles most system-wide and application-wide settings. For any GUI application that uses Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any time.”

QtGui is needed here if we want to display widget. If no widget is to be displayed then this line can be dropped.

import sys
from PyQt4 import QtGui

The main() function in C is analogous to the following line in python:

if __name__==’__main__’:
a=QtGui.QApplication(sys.argv)
# this will create an application named ‘a’initialised with a command-line parameter.

sys.exit(a.exec_())
#application is executed.

Now if we want to display any widget or window, we have to write it between the above two lines.

widget=QtGui.QWidget()
widget.setWindowTitle(‘simple’)
widget.show()

Running the final code will display a Widget.

#!/usr/bin/python

import sys
from PyQt4 import QtGui

if __name__==’__main__’:
a=QtGui.QApplication(sys.argv)

widget=QtGui.QWidget()
widget.setWindowTitle(‘simple’)
widget.show()
sys.exit(a.exec_())

helloworld

Advertisements

About Shantanu Sharma

Currently working as Software R&D member in Samsung R&D India.

Posted on October 23, 2013, in Qt: The Face Of Embedded and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s