Blog Archives

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