#!/usr/bin/env python

#****************************************************************************
#** $Id: sqltable4.py 322023 2004-06-19 20:33:37Z sedwards $
#**
#** Copyright (C) 1992-1998 Troll Tech AS.  All rights reserved.
#**
#** This file is part of an example program for PyQt.  This example
#** program may be used, distributed and modified without limitation.
#**
#*****************************************************************************/

import sys
from qt import *
from qtsql import *

from dbconnect import createConnection

TRUE  = 1
FALSE = 0

class CustomTable(QDataTable):
    def __init__(self, cursor, autoPopulate = FALSE, parent = None, name = None):
        QDataTable.__init__(self, cursor, autoPopulate, parent, name)

    def paintField(self, p, field, cr, b):
        if not field:
            return
        fn = str(field.name())
        if fn in ("salary", "monsalary"):
            v = field.value().toDouble()
            if v < 0:
                p.setPen(QColor("red"))
            value = QString(u"%.2f \u20ac" % v)
            #print unicode(value).encode("iso-8859-15")
            p.drawText(2, 2, cr.width()-6, cr.height()-4,
                        Qt.AlignRight|Qt.AlignVCenter, value)
        elif fn == "statusid":
            query = QSqlQuery("SELECT name FROM status WHERE id=%s" %
                              field.value().toString())
            value = ""
            if query.next():
                value = query.value(0).toString()
            p.drawText(2, 2, cr.width()-4, cr.height()-4,
                        self.fieldAlignment(field), value)
        else:
            QDataTable.paintField(self, p, field, cr, b)


class StatusPicker(QComboBox):
    def __init__(self, parent = None, name = None):
        QComboBox.__init__(self, parent, name)
        cur = QSqlCursor("status")
        cur.select(cur.index("id"))
        while cur.next():
            self.insertItem(cur.value("name").toString(), cur.value("id").toInt())


class CustomSqlEditorFactory(QSqlEditorFactory):
    def __init__(self):
        QSqlEditorFactory.__init__(self)

    def createEditor(self, parent, field):
        try:
            if str(field.name()) == "statusid":
                return StatusPicker(parent)
        except AttributeError:
            pass
        return QSqlEditorFactory.createEditor(self, parent, field)


class StaffCursor(QSqlCursor):
    def __init__(self):
        QSqlCursor.__init__(self, "staff")
        monSalary = QSqlFieldInfo("monsalary", QVariant.Double)
        self.append(monSalary)
        self.setCalculated(monSalary.name(), TRUE)

    def calculateField(self, name):
        if str(name) == "monsalary":
            return QVariant(self.value("salary").toDouble() / 12)
        return QVariant(QString.null)


class Table(CustomTable):
    def __init__(self):
        #self.staffCursor = QSqlCursor("staff")
        self.staffCursor = StaffCursor()
        QDataTable.__init__(self, self.staffCursor)
        self.propMap = QSqlPropertyMap()
        self.editorFactory = CustomSqlEditorFactory()
        self.propMap.insert("StatusPicker", "statusid")
        self.installPropertyMap(self.propMap)
        self.installEditorFactory(self.editorFactory)
        for cn, ch in (("forename", "Forename"),
                       ("surname",  "Surname" ),
                       ("salary",   "Annual Salary"),
                       ("monsalary","Monthly Salary"),
                       ("statusid", "Status")):
            self.addColumn(cn, ch)
        self.order = QStringList("surname")
        self.order.append("forename")
        self.setSort(self.order)
        self.refresh()


if __name__=='__main__':
    app = QApplication(sys.argv)
    #app.setFont(QFont("Verdana", 11))

    if createConnection():
        t = Table()
        app.setMainWidget(t)
        t.resize(600, 250)
        t.show()
        app.exec_loop()


