Page List

Sunday, January 22, 2012

Qt Tutorial #1-6 Building Blocks Galore

This is from Qt Tutorial #1-6 Building Blocks Galore


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

'''
    PyQt4 conversion of Qt Tutorial 6
    
    This example shows how to encapsulate two widgets into a new component 
    and how easy it is to use many widgets. The custom widget (LCDRange) 
    is used as a child widget. 
    
    Behaviour: move a slider to change the related number display.
    
    Note: example uses 'nested' layouts to create the GUI
          
last modified: 2012-01-19 jg
ref: 
    http://doc.trolltech.com/3.3/tutorial1-06.html
'''
import sys
from PyQt4.QtGui import (QApplication, QWidget, QPushButton, QFont,
                         QVBoxLayout, QSlider, QLCDNumber, QGridLayout)
from PyQt4.QtCore import (Qt)

class LCDRange(QWidget):
    '''
        A two digit QLCDNumber and QSlider widget.
    '''
    def __init__(self, parent=None):
        super(LCDRange, self).__init__(parent)

        lcd = QLCDNumber(2, self);
        slider = QSlider(Qt.Horizontal, self);
        slider.setRange(0, 99);
        slider.setValue(0);
        slider.valueChanged.connect(lcd.display)

        layout = QVBoxLayout()
        layout.addWidget(lcd)
        layout.addWidget(slider)
        self.setLayout(layout)

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

        quitBtn = QPushButton('Quit', self)
        quitBtn.setFont(QFont("Times", 18, QFont.Bold))
        quitBtn.clicked.connect(QApplication.instance().quit)

        grid = QGridLayout()
        for r in range(4):
            for c in range(4):
                grid.addWidget(LCDRange(self), r, c)

        # nesting layouts
        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addWidget(quitBtn)

        self.setLayout(vbox)

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

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

if __name__ == '__main__':
    main()