Sunday, January 22, 2012

Qt Tutorial #1-5 Building Blocks

This is from Qt Tutorial #1 Building Blocks

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

'''
    PyQt4 conversion of Qt Tutorial 5
    
    This example shows how to create and connect together several widgets 
    by using signals and slots, resize events are handled automatically.
    
    Behavior
        The LCD number reflects everything you do to the slider, and the widget 
        handles the resizing automatically. 
        Notice that the LCD number widget changes in size when the window is resized 
        (because it can), but the others stay about the same (because otherwise they 
        would look stupid).
    
    Note: The original code subclassed QVBox
          Here, we subclass QWidget and set its layout to QVBoxLayout 
        
last modified: 2012-01-19 jg
ref: 
    http://doc.trolltech.com/3.3/tutorial1-05.html
'''
import sys
from PyQt4.QtGui import (QApplication, QWidget, QPushButton, QFont,
                         QVBoxLayout, QSlider, QLCDNumber)
from PyQt4.QtCore import (Qt)

class MyWidget(QWidget):    # MyWidget subclasses QWidget
    def __init__(self, parent=None, name=''):
        super(MyWidget, self).__init__(parent)  # initialise base (QWidget) class
        if name:
            self.setObjectName(name)

        layout = QVBoxLayout()
        self.setLayout(layout)

        quitBtn = QPushButton('Quit', self)
        quitBtn.setFont(QFont("Times", 18, QFont.Bold))
        layout.addWidget(quitBtn)

        quitBtn.clicked.connect(QApplication.instance().quit)

        lcd = QLCDNumber(2, self);  # two digit number display
        layout.addWidget(lcd)

        slider = QSlider(Qt.Horizontal, self);  # Qt constant
        slider.setRange(0, 99);     # number range
        slider.setValue(0);         # initial value
        layout.addWidget(slider)

        # forward slider value changes to the lcd display method
        slider.valueChanged.connect(lcd.display)

def main():
    app = QApplication(sys.argv)    # required

    w = MyWidget(name='slider')
    w.show()
    sys.exit(app.exec_())   # start main event loop, exit when app closed


if __name__ == '__main__':
    main()