Qt for Python Tutorial HelloWorld

From Qt Wiki
Revision as of 14:11, 23 February 2015 by Maintenance script (talk | contribs)
Jump to navigation Jump to search


English ["French":http://qt-devnet.developpez.com/tutoriels/pyside/simplissimus/#LIII-B] 한국어 日本語

* Note: this article is a member of the multipart PySide-Newbie-Tutorials

Your first PySide application

If you followed the Setting_up_PySide wiki page to install PySide, you should now have a full blown copy of PySide on your machine to start developing Qt+Python GUI applications. As with any other programming framework, you start with the traditional "Hello World" program.

Here is a simple example of an Hello World in PySide:

<br />#!/usr/bin/python

# Import PySide classes<br />import sys<br />from PySide.QtCore import *<br />from PySide.QtGui import *

# Create a Qt application<br />app = QApplication(sys.argv)
# Create a Label and show it<br />label = QLabel(&quot;Hello World&amp;quot;)<br />label.show()
# Enter Qt application main loop<br />app.exec_()<br />sys.exit()<br />

With PySide desktop applications, you must always start your file by importing PySide.QtCore and PySide.QtGui classes. These classes have the main functions for building PySide applications. For instance, PySide.QtGui contains functions for dealing with widgets while PySide.QtCore contains methods for handling signals and slots, and controlling the application.

After the imports, you create a QApplication which is the main Qt application. As Qt can receive arguments from command line, you must pass any arguments to the QApplication object. Usually, you don't need to pass any arguments so you can leave it as it is.

After the creation of the application object, we have created a QLabel object. A QLabel is a widget that can present text (simple or rich, like html), and images. Note that after the creation of the label, we are calling the method show which will present the label to the user.

Finally, we call app.exec_() which will enter the Qt main loop and start to execute the Qt code. In reality, it is only here that the label will be shown, but this can be ignored for now.

Displaying html in the label

As mentioned previously, you can insert html tags in the label to present rich text. Try changing the code which creates the label for something like:

<br />label = QLabel(&quot;&lt;font color=red size=40&amp;gt;Hello World&amp;lt;/font&amp;gt;&quot;)<br />

and you will the the "Hello World&quot; now bigger and red. You can try to change to another color, another size, or make it blink! Or you can create other elements instead of the QLabel, like QPushButton, or others.