Showing posts with label python qt pyqt. Show all posts
Showing posts with label python qt pyqt. Show all posts

Sunday, July 12, 2009

Hello World in PyQt

Lately I've been looking to python as a quick way to hammer out a qt application. I find it quite nice so I have concocted as small example with my comments. Perhaps this tutorial will help make it sink in for some people. If you have any suggestions or if there is anything you are unclear about or have questions about feel free to ask in the comments section.


I called it "HelloWorld.py", but I have added a few other non-"hello world" related pieces of code to show how they work in PyQt. So without further ado I give to you: "HelloWorld.py"

#first we have to import all of out needed libraries
import sys #this is used for system arguments
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# I could have left out the from and just said import PyQt4
# The main benefit is that I now don't have to type PyQt4.QtGui.QWidget()
# So I feel it improves clarity, you'll want to find what works best for you.



#setting up the application, usually this isn't the structure you would use, however I don't want to get into python classes here.
app = QApplication(sys.argv)

#here I am declaring all the widgets I will need to use later
widget = QWidget()
helloButton = QPushButton("Say Hello World!")
textEdit = QTextEdit()
label = QLabel("Hide me!")
vBoxLayout = QVBoxLayout()

#in this section I am setting up the widget layout
widget.setLayout(vBoxLayout)
vBoxLayout.addWidget(helloButton)
vBoxLayout.addWidget(label)
vBoxLayout.addWidget(textEdit)

#this next line makes it so that when the "-" button is pressed at the start of a line a bulleted list begins
textEdit.setAutoFormatting(QTextEdit.AutoBulletList)

# here I am going declare a python native function, that we will connect to "helloButton"
def sayHelloConsole():
print "Hello World!!!" # this function has changed for latest python. It will become print("Hello World")


#Now I will connect the signals
QObject.connect(helloButton, SIGNAL("clicked()"), sayHelloConsole)
QObject.connect(helloButton, SIGNAL("clicked()"), label, SLOT("hide()"))
#the main differences there is when I had a Qt slot as opposed to a python function to connect to I had to put it in the form SLOT().


#Show the widget & start the application
widget.show()
sys.exit(app.exec_())
I hope this helps someone. Now you can get started learning pyqt/pykde so you can contribute to Kubuntu or what ever your distro of choice may be. If there is enough interest I'll post another article on here using pyKDE libraries as well, but that shouldn't be too difficult.