Wednesday, January 25, 2012

Qt 4.8 Address Book Tutorial - Part 1

The following code is based on the Qt Address Book Tutorial. It consists of seven parts. To see an alternative Python version of the code from this tutorial check your PyQt4 install directory under examples/tutorials/addressbook. The code below is from Part 1 - Designing the User Interface.



#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''
    PyQt4 conversion of Qt Tutorial 'Address Book'
    
    This first part covers the design of the basic graphical user interface (GUI)
    for our address book application. The first step in creating a GUI program is 
    to design the user interface. Here the our goal is to set up the labels and 
    input fields to implement a basic address book.
    
    
last modified: 2012-01-23 jg
ref: 
    http://developer.qt.nokia.com/doc/qt-4.8/tutorials-addressbook.html
    http://developer.qt.nokia.com/doc/qt-4.8/tutorials-addressbook-part1.html
'''
import sys
from PyQt4.QtGui import (QApplication, QWidget, QLabel, QTextEdit, QLineEdit,
                         QGridLayout)
from PyQt4.QtCore import (Qt)

class AddressBook(QWidget): # subclass QWidget

    def __init__(self, parent=None):
        super(AddressBook, self).__init__(parent)   # initialise the base class

        # create input labels and fields
        nameLabel = QLabel(self.tr("Name:"))
        nameLine = QLineEdit(self)

        addrLabel = QLabel(self.tr("Address:"))
        addrText = QTextEdit(self)

        # create and populate layout
        mainLayout = QGridLayout()
        mainLayout.addWidget(nameLabel, 0, 0)
        mainLayout.addWidget(nameLine, 0, 1)
        mainLayout.addWidget(addrLabel, 1, 0, Qt.AlignTop)
        mainLayout.addWidget(addrText, 1, 1)

        # set this objects layout and window title
        self.setLayout(mainLayout)
        self.setWindowTitle(self.tr("Simple Address Book"))


def main():
    app = QApplication(sys.argv)    # required for all GUI applications

    ab = AddressBook()
    ab.show()                       # make me visible

    sys.exit(app.exec_())           # start main event thread

if __name__ == '__main__':
    main()