PyQt4: Getting into depth

Now let us add some functionalities to the window generated. For that, I am listing the APIs to create any widget and handling signals & slots:

To create any widget:

1. textbox=QtGui.QTextBox(“content of the text box”)

Note:This will work fine unless until you need to access this textbox in some function treating it as a global variable. To avoid the errors in future, use this line:

self.textbox=QtGui.QTextBox(“content of the text box”)

adding self in beginning will make textbox an attribute of the window under which it is created.

2. self.label=QtGui.QLabel(“content of the label”)

3. self.pushbutton=QtGui.QPushButton(“text on pushbutton”)

to create singnals and slots:

This can be achieved in two ways:
1.New version API- QtCore.QObject.Connect method:
QtCore.QObject.Connect(<name of the object generating signal>,QtCore.SIGNAL(“<signal name>”), <slot>)


QtCore.QObject.Connect(self.pushbutton,QtCore.SIGNAL(“clicked()”),   self.on_pushbutton_click)

def on_pushbutton_click(self):
#write the function here to be executed on pushbutton being clicked, e.g..
self.label.setText(“pushbutton is clicked”)

2.Old style API-

<object-name>.<signal>.connect(<slot function>)
Example: button.clicked.connect(self.onClicked)

However,Prefer the first method.

So the Complete Code is as follows:
#! /usr/bin/python

import sys
from PyQt4 import QtGui, QtCore

class signalslots(QtGui.QMainWindow):

def __init__(self):
super(signalslots, self).__init__()

btn1 = QtGui.QPushButton(“Button 1”, self)
btn1.move(30, 50)

btn2 = QtGui.QPushButton(“Button 2”, self)
btn2.move(150, 50)



self.setGeometry(300, 300, 290, 150)
self.setWindowTitle(‘signals and slots’)

def buttonClicked(self):
sender = self.sender()
self.statusBar().showMessage(sender.text() + ‘ was pressed’)

if __name__==’__main__’:
app = QtGui.QApplication(sys.argv)
ex = signalslots()

Note: Here appending self prior to btn1 (self.btn1) is not needed because the btn1 is not used outside its scope. However, always use self to avoid any confusion.


Signals and slots
Signals and slots
pushing button 2
pushing button 2





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: Logo

You are commenting using your 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