Since foss.in 2006 I have got a special Interest in KDE and GUI development. Its up to such extent that I installed kubuntu-desktop in my laptop and started using it, at laeast when am home. I have also started learning PyQt, ultimately wish to learn PyKDE and contribute to KDE. I have started working with the Qt tuorial, which is in C++. So I have to write the change it to Python i.e. PyQt. Its not a much a problem, rather easy too. But, example 4 had some OOPs in it and I haven’t tried much OOPs in Python before. So, here goes my first OOP PyQt code, which I came up with a bit of struggle for some time.
The original Qt tutorial is here…
class MyWidget : public QWidget
MyWidget( QWidget *parent=0, const char *name=0 );
MyWidget::MyWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
setMinimumSize( 200, 120 );
setMaximumSize( 200, 120 );
QPushButton *quit = new QPushButton( "Quit", this, "quit" );
quit->setGeometry( 62, 40, 75, 30 );
quit->setFont( QFont( "Times", 18, QFont::Bold ) );
connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );
int main( int argc, char **argv )
QApplication a( argc, argv );
w.setGeometry( 100, 100, 200, 120 );
a.setMainWidget( &w );
And here is my PyQt code…
from qt import *
"""MyWidget is a custom widget to display a quit button.
This widget is inheritted from QWidget"""
def __init__(self, parent=None, name=None):
quitbutton = QPushButton("Quit", self, "quitbutton")
quitbutton.setGeometry(62, 40, 75, 30)
quitbutton.setFont( QFont("Serif", 16, QFont.Bold))
self.connect( quitbutton, SIGNAL("clicked()"), qApp, SLOT("quit()"))
app = QApplication(sys.argv)
w = MyWidget()
w.setGeometry(100, 100, 200, 120)
The testing part of the code was how to transfer the ‘constructor’ in C++ to Python. Although Python is Object Oriented, we do not have constructor as in C++. We rather have a __init__ method, which can act as initializer, the job which the constructor does and the same reason for people to call __init__ to be the constructor in Python (which I found to be not the right way, from the Python Documentation and various other sources).
Actually, if you see the code it is pretty obvious that the Python code is easier to understand, easier to code and easier to maintain. Things are small and simple, but still your job gets done. And also, I realized that we can effectively transform (or port) an existing C++ code (or any of the many programing language) into Python code. Hope, I continue on this learning curve and learn things soon, end up writing cool Python Apps contributing to the community.