python logo


Category: QT4

PyQt4 textbox

pyqt textbox PyQt4 textbox example

In this article you will learn how to interact with a textbox using PyQt4.

If you want to display text in a textbox (QLineEdit) you could use the setText() method.

Related course:

PyQt4 QLineEdit


The textbox example below changes the text if the button is pressed.


import sys
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *

# create our window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle('Textbox example @pythonspot.com')

# Create textbox
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)

# Set window size.
w.resize(320, 150)

# Create a button in the window
button = QPushButton('Click me', w)
button.move(20,80)

# Create the actions
@pyqtSlot()
def on_click():
textbox.setText("Button clicked.")

# connect the signals to the slots
button.clicked.connect(on_click)

# Show the window and run the app
w.show()
app.exec_()

The text field is created with the lines:


textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)

The button (from screenshot) is made with:


button = QPushButton('Click me', w)

We connect the button to the on_click function by:


# connect the signals to the slots
button.clicked.connect(on_click)

This function sets the textbox using setText().

Download PyQT Code (Bulk Collection)

Qt4 buttons

PyQt4 button example PyQt4 button example

PyQt4 (Qt4) supports buttons through the QPushButton widget.

We extend the code to display a button in the center of the window.

The button will show a tooltip if hovered and when pressed will close the program.

Related course:

PyQt4 button example


The example below adds a button to a PyQt4 window.


#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Add a button
btn = QPushButton('Hello World!', w)
btn.setToolTip('Click to quit!')
btn.clicked.connect(exit)
btn.resize(btn.sizeHint())
btn.move(100, 80)

# Show window
w.show()

sys.exit(a.exec_())

PyQt4 signals and slots


A button click should do something. To do so, you must use signals and slots.

If a user does an action such as clicking on a button, typing text in a box – the widget sends out a signal. Signals can be connected with a slot, that acts as a receiver and acts on it.


import sys
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *

# create our window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle('Button click example @pythonspot.com')

# Create a button in the window
btn = QPushButton('Click me', w)

# Create the actions
@pyqtSlot()
def on_click():
print('clicked')

@pyqtSlot()
def on_press():
print('pressed')

@pyqtSlot()
def on_release():
print('released')

# connect the signals to the slots
btn.clicked.connect(on_click)
btn.pressed.connect(on_press)
btn.released.connect(on_release)

# Show the window and run the app
w.show()
app.exec_()

Download PyQT Code (Bulk Collection)

Qt4 window

pyqt window PyQt4 window on Ubuntu

In this tutorial you will learn how to create a graphical hello world application with PyQT4.

PyQT4, it is one of Pythons options for graphical user interface (GUI) programming.

Related course:

PyQt4 window example:


This application will create a graphical window that can be minimized, maximimzed and resized it.


#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Show window
w.show()

sys.exit(a.exec_())

The PyQT4 module must be immported, we do that with this line:


from PyQt4.QtGui import *

We create the PyQT4 application object using QApplication():


a = QApplication(sys.argv)

We create the window (QWidget), resize, set the tittle and show it with this code:


w = QWidget()
w.resize(320, 240)
w.setWindowTitle("Hello World!")

Don’t forget to show the window:


# Show window
w.show()

You can download a collection of PyQt4 examples:
 
Download PyQT Code (Bulk Collection)

QT4 Messagebox

PyQT4 offers message box functionality using several functions.
Messageboxes included in PyQT4 are: question, warning, error, information, criticial and about box.

Related course: Create GUI Apps with Python PyQt5

PyQt4 mesagebox

The code below will display a message box with two buttons:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Show a message box
result = QMessageBox.question(w, 'Message', "Do you like Python?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

if result == QMessageBox.Yes:
print('Yes.')
else:
print('No.')

# Show window
w.show()

sys.exit(a.exec_())

Result:

qtMessagebox question qtMessagebox question

There are different types of messageboxes that PyQT4 provides.

PyQT4 Warning Box


You can display a warning box using this line of code:

QMessageBox.warning(w, "Message", "Are you sure you want to continue?")

PyQT4 Information box


We can display an information box using QMessageBox.information()

QMessageBox.information(w, "Message", "An information messagebox @ pythonspot.com ")

Result:

QMessageBox Info QMessageBox Info

PyQT4 Critical Box


If something goes wrong in your application you may want to display an error message.

QMessageBox.critical(w, "Message", "No disk space left on device.")



Result:

QMessagebox QMessagebox

PyQT4 About box


We have shown the question box above.

QMessageBox.about(w, "About", "An example messagebox @ pythonspot.com ")



Result:

qt Messagebox qt Messagebox

Download PyQT Code (Bulk Collection)

Menu with PyQt4

PyQT Menu pythonspot PyQT Menu

PyQt4 menus appear in the top of the window bar. A menu gives the user control over the application and is often location in the top of the window.

The QMainWindow class creates the main application window. This class has a method named menuBar() which adds the title bar.

Menus can be added to the title bar using addMenu(). Inside each menu you can add a command using the addAction method.

Related course:

PyQt4 menubar


This code will add a menu to your qt4 app:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Create main menu
mainMenu = w.menuBar()
mainMenu.setNativeMenuBar(False)
fileMenu = mainMenu.addMenu('&File')

# Add exit button
exitButton = QAction(QIcon('exit24.png'), 'Exit', w)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(w.close)
fileMenu.addAction(exitButton)

# Show window
w.show()

sys.exit(a.exec_())

Download PyQT Code (Bulk Collection)

QT4 Widgets

We have various widgets that we can access with PyQT. Including:

  • Textbox
  • Combobox
  • Calendar
For more widgets we suggest using the GUI creation tool covered in the next tutorial.

Related course: Create GUI Apps with PyQt5

Textbox widget
Input fields are present in nearly every application. In PyQT4 an input field can be created using the QLineEdit() function.

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 100)

# Set window title
w.setWindowTitle("PyQT Python Widget!")

# Create textbox
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)

# Show window
w.show()

sys.exit(a.exec_())
qt textbox qt textbox

Combobox
A combobox can be used to select an item from a list.

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 100)

# Set window title
w.setWindowTitle("PyQT Python Widget!")

# Create combobox
combo = QComboBox(w)
combo.addItem("Python")
combo.addItem("Perl")
combo.addItem("Java")
combo.addItem("C++")
combo.move(20,20)

# Show window
w.show()

sys.exit(a.exec_())
qt combobox qt combobox

Calendar widget
The PyQT4 library has a calendar widget, you can create it using the QCalendarWidget() call.

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("PyQT Python Widget!")

# Create calendar
cal = QCalendarWidget(w)
cal.setGridVisible(True)
cal.move(0, 0)
cal.resize(320,240)

# Show window
w.show()

sys.exit(a.exec_())

Result:

calendar qt calendar qt

Download PyQT Code (Bulk Collection)

QT4 Table

We can show a table using the QTableWidget, part of the PyQt module.  We set the title, row count, column count and add the data.

Related course:

Qt4 Table example


An example below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQt Table

QTableWidget labels


You can set the header using the setHorizontalHeaderLabels() function. The same applies for vertical labels. A demonstration below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQT Table

QTableWidget click events


We can detect cell clicks using this procedure, first add a function:

# on click function
table.cellClicked.connect(cellClick)



Then define the function:

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

The Python programming language starts counting with 0, so when you press on (1,1) you will see (0,0). Full code to detect table clicks:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# on click function
table.cellClicked.connect(cellClick)

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

If you want to show the cell/row numbers in a non-programmer way use this instead:

def cellClick(row,col):
print "Click on " + str(row+1) + " " + str(col+1)



Tooltip text


We can set tooltip (mouse over) text using the method. If you set tooltips on non-existing columns you will get an error.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# tooltip text
table.horizontalHeaderItem(0).setToolTip("Column 1 ")
table.horizontalHeaderItem(1).setToolTip("Column 2 ")

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table tooltips PyQT Table tooltips

Download PyQT Code (Bulk Collection)

QT4 Tabs

Tabs are very useful in graphical applications. They appear in webbrowsers, text editors and any other apps.  To create a tabbed window, you need to call the  QTabWidget()  function.  Every tab is a QWidget() which you have seen before.  You can connect the QWidgets with the QTabWidget with the function:

tabs.addTab(tab1,"Tab 1")

where the first parameter is the tab object and the second the name that appears on the screen. We added some buttons to the first tab (QWidget).

Related course:

Example code:

from PyQt4 import QtGui
from PyQt4 import QtCore
import sys

def main():

app = QtGui.QApplication(sys.argv)
tabs = QtGui.QTabWidget()

# Create tabs
tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()
tab4 = QtGui.QWidget()

# Resize width and height
tabs.resize(250, 150)

# Set layout of first tab
vBoxlayout = QtGui.QVBoxLayout()
pushButton1 = QtGui.QPushButton("Start")
pushButton2 = QtGui.QPushButton("Settings")
pushButton3 = QtGui.QPushButton("Stop")
vBoxlayout.addWidget(pushButton1)
vBoxlayout.addWidget(pushButton2)
vBoxlayout.addWidget(pushButton3)
tab1.setLayout(vBoxlayout)

# Add tabs
tabs.addTab(tab1,"Tab 1")
tabs.addTab(tab2,"Tab 2")
tabs.addTab(tab3,"Tab 3")
tabs.addTab(tab4,"Tab 4")

# Set title and show
tabs.setWindowTitle('PyQt QTabWidget @ pythonspot.com')
tabs.show()

sys.exit(app.exec_())

if __name__ == '__main__':
main()

Result:

PyQT Tabs PyQT Tabs

Download PyQT Code (Bulk Collection)

QT4 File Dialog

In this short tutorial you will learn how to create a file dialog and load its file contents. The file dialog is needed in many applications that use file access.

Related course:

File Dialog Example
To get a filename (not file data) in PyQT you can use the line:

filename = QFileDialog.getOpenFileName(w, 'Open File', '/')

If you are on Microsoft Windows use

filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\')

An example below (includes loading file data):

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Get filename using QFileDialog
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')
print(filename)

# print file contents
with open(filename, 'r') as f:
print(f.read())

# Show window
w.show()

sys.exit(a.exec_())

Result (output may vary depending on your operating system):

pyqt_file_open PyQt File Open Dialog.

Download PyQT Code (Bulk Collection)

QT4 Pixmaps (Images)

In this article we will demonstrate how to load and display images in an PyQT window. We can display images in a PyQT window using the Pixmap widget.

PyQt4-load-image An image loaded in a PyQt4 window.

Related course:

Introduction


The constructor of Pixmap takes the image path as parameter:

pixmap = QPixmap(os.getcwd() + '/logo.png')

This image needs to be in the same directory as your program. The QPixmap widget supports png and jpeg.  Example code below.

PyQT load image in Pixmap


We create a standard QWidget as we have done before. Then we add the QPixmap widget inside which will load the image. The Pixmap is attached to a label which is drawn to the screen.

import os
import sys
from PyQt4.QtGui import *

# Create window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ")

# Create widget
label = QLabel(w)
pixmap = QPixmap(os.getcwd() + '/logo.png')
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())

# Draw window
w.show()
app.exec_()

Download PyQT Code (Bulk Collection)

Result:

pyqt Pixmap pyqt Pixmap

QT4 Progressbar

In this article we will demonstrate how to use the progressbar widget.  The progressbar is different from the other widgets in that it updates in time.

Related course:

QT4 Progressbar Example
Let’s start with the code:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT

class QProgBar(QProgressBar):

value = 0

@pyqtSlot()
def increaseValue(progressBar):
progressBar.setValue(progressBar.value)
progressBar.value = progressBar.value+1

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("PyQT4 Progressbar @ pythonspot.com ")

# Create progressBar.
bar = QProgBar(w)
bar.resize(320,50)
bar.setValue(0)
bar.move(0,20)

# create timer for progressBar
timer = QTimer()
bar.connect(timer,SIGNAL("timeout()"),bar,SLOT("increaseValue()"))
timer.start(400)

# Show window
w.show()

sys.exit(a.exec_())

The instance bar (of class QProgBar) is used to hold the value of the progressbar.  We call the function setValue() to update its value.  The parameter w is given to attach it to the main window. We then move it to position (0,20) on the screen and give it a width and height.

To update the progressbar in time we need a QTimer().  We connect the widget with the timer, which calls the function increaseValue().  We set the timer to repeat the function call every 400 milliseconds.  You also see the words SLOT and SIGNAL.  If a user does an action such as clicking on a button, typing text in a box - the widget sends out a signal.  This signal does nothing, but it can be used to connect with a slot, that acts as a receiver and acts on it.

Result:

PyQT Progressbar PyQT Progressbar

Download PyQT Code (Bulk Collection)

Creating a web-browser with Python and PyQT

PyQt4 GUI tutorial

In this tutorial we will teach you how to create a graphical application with PyQT4. This will work on any platform that supports PyQT4 including Windows, Linux, UNIX, Android, OS X and iOS.

Related course:

PyQt4 installation


PyQt does not include Qt itself – you may have to obtain it separately.
The homepage for PyQt is https://www.riverbankcomputing.com/software/pyqt/.

You will need to install some packages:


sudo pip install pyqt
sudo apt-get install qt4-designer
sudo apt-get install pyqt4-dev-tools
sudo apt-get install python-kde4

If python-kde4 cannot be found update your repository to find it. If you are on Ubuntu use this link.

Building a PyQT4 GUI


Now we can use the QT Designer application. It saves us from writing tons of layout code that you may be used to when writing HTML. Start qt4-designer from your applications menu. The QT Designer application will appear.

QT_Designer QT Designer

Press Dialog without Buttons and press Create. You can now drag any component from the widget box to the form. Simple drag and drop. We added a button, label and a pixmap. (I took a random image from the web for the pixmap)

QT_KDE_Dialog QT KDE Dialog

Our window looks like the image above. Press Form > Viewcode. We will get a popup box with the form code in… C++! That is great, but we want the Python code. Press File > Save as > form.ui.

The file test.ui contains your form described in XML format. (You can view it in a text editor) Open a console and type:


pyuic4 form.ui > form.py

Running the file does nothing. Create a new file called gui.py

Paste the code below:


import sys
from PyQt4 import QtCore, QtGui
from form import Ui_Dialog

class MyDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)

if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyDialog()
myapp.show()
sys.exit(app.exec_())

Run with:


python gui.py

This will open our graphical interface. Pressing on the OK button will simply close the application.

pyqt_window-300x215 PyQt Window with QButton

We want to add some action when the OK button is pressed. We add these three lines to the code:


self.ui.pushButton.clicked.connect(self.OK)

def OK(self):
print 'OK pressed.'

pyqt4 app example pyqt4 app example

Download PyQT4 Examples (Bulk Collection)

You may like: Create a webbrowser with PyQT4 or PyQt4 Overview

QML and PyQT: Creating a GUI (tutorial)

If you have not done our first PyQT tutorial yet, you should do it, it’s fun! In this tutorial we will use PyQT4 and a user interface markup language, a language that describes the graphical  user interfaces and controls

Related course:

QML and PyQT


An excerpt of user interface markup graphical user interfaces and language code could look like:

 Rectangle {
id: simplebutton
color: "grey"
width: 150; height: 75

Essentially the language tells what the interface should look like. The language we will be using is called QML.

QTCreator


Start a programmed called QTCreator.   The tutorial will be quite graphical to help you through the whole process. Simply type qtcreator in the terminal or start it from the menu list.  This screen should pop up:

qtcreator qtcreator

Creating a GUI


Press the big New Project button. Select QT Quick Application from the menu below. Finally press Choose on the bottom right.

qtquick qtquick

A new popup will appear:

kde create kde create

Type a name and a valid path to save your project. Then press Next.  Select QT Quick 2.0 from the menu list. Press Next. Press Finish. Immediately a user interface defined in the QML language will appear.

qt quick qt quick

Like all great programmers we are going to solve things the most lazy way possible.  Instead of typing all the QML code by hand we are going to press the Design button that is on the left of the screen.  A drag and drop screen should appear now.

draganddrop draganddrop

We drag an image onto the area and select the source on the right. Save the project. Open a terminal and locate the qml file you just created. Alternatively you could simply copy the code in the edit box and save it to a .qml file. Enter the command:

qmlviewer main.qml

This will display the windows as defined in the qml file without any functionality. It is simply a viewer for the interface.  We then create some code to load this QML definition:

import sys

from PyQt4.QtCore import QDateTime, QObject, QUrl, pyqtSignal
from PyQt4.QtGui import QApplication
from PyQt4.QtDeclarative import QDeclarativeView

app = QApplication(sys.argv)

# Create the QML user interface.
view = QDeclarativeView()
view.setSource(QUrl('main.qml'))
view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
view.setGeometry(100, 100, 400, 240)
view.show()

app.exec_()

Finally we modify the first line main.qml to:

import Qt 4.7

Simply because our QtQuick was missing. Running

python run.py

Will now display our user interface as defined by QML:

QML_PyQT QML and PyQT

All of the code is simply PyQT, so you could add code like in the previous tutorial. These are the two methods to create a graphical interface with PyQT.  This method may be more loosely coupled to the code compared to the method of creating a GUI with QT in the previous tutorial. Despite that both are valid methods.

Download PyQT4 Examples (Bulk Collection)

You may like: Application GUI with PyQT4 or the PyQt4 Tutorials