summaryrefslogtreecommitdiffstats
path: root/examples3/SQL/sqlsubclass5.py
blob: 07cc90a722ec2b4ba43dd8bb65d45dd698b916b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python

#****************************************************************************
#** $Id: sqlsubclass5.py,v 1.3 2002/07/06 13:35:41 phil Exp $
#**
#** Copyright (C) 1992-1998 Troll Tech AS.  All rights reserved.
#**
#** This file is part of an example program for PyTQt.  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(TQDataTable):
    def __init__(self, cursor, autoPopulate = FALSE, parent = None, name = None):
        TQDataTable.__init__(self, cursor, autoPopulate, parent, name)

    def paintField(self, p, field, cr, b):
        if not field:
            return
        fn = str(field.name())
        if fn == "pricesid":
            query = TQSqlQuery("SELECT name FROM prices 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)
        elif fn == "quantity":
            p.drawText(2, 2, cr.width()-6, cr.height()-4,
                        TQt.AlignRight|TQt.AlignVCenter,  field.value().toString())
        elif fn in ("price", "cost"):
            v = field.value().toDouble()
            if v < 0:
                p.setPen(TQColor("red"))
            value = TQString(u"%.2f \u20ac" % v)
            p.drawText(2, 2, cr.width()-6, cr.height()-4,
                        TQt.AlignRight|TQt.AlignVCenter, value)
        elif fn == "paiddate":
            if field.value().toDate().isNull():
                v = TQString("not yet")
                p.setPen(TQColor("red"))
            else:
                v = field.value().toDate().toString(TQt.LocalDate)
            p.drawText(2, 2, cr.width()-4, cr.height()-4,
                        TQt.AlignHCenter|TQt.AlignVCenter, v)
        else:
            TQDataTable.paintField(self, p, field, cr, b)


class InvoiceItemCursor(TQSqlCursor):
    def __init__(self):
        TQSqlCursor.__init__(self, "invoiceitem")

        productPrice = TQSqlFieldInfo("price", TQVariant.Double)
        self.append(productPrice)
        self.setCalculated(productPrice.name(), TRUE)

        productCost = TQSqlFieldInfo("cost", TQVariant.Double)
        self.append(productCost)
        self.setCalculated(productCost.name(), TRUE)

    def calculateField(self, name):
        fn = str(name)
        if fn == "productname":
            query = TQSqlQuery("SELECT name FROM prices WHERE id=%d;" %
                              (self.field("pricesid").value().toInt()))
            if query.next():
                return query.value(0)
        elif fn == "price":
            query = TQSqlQuery("SELECT price FROM prices WHERE id=%d;" %
                              (self.field("pricesid").value().toInt()))
            if query.next():
                return query.value(0)
        elif fn == "cost":
            query = TQSqlQuery("SELECT price FROM prices WHERE id=%d;" %
                              (self.field("pricesid").value().toInt()))
            if query.next():
                return TQVariant(query.value(0).toDouble() * 
                                self.value("quantity").toDouble())
        return TQVariant(TQString.null)

    def primeInsert(self):
        buffer = self.editBuffer()
        buffer.setValue("id", TQVariant(0))
        buffer.setValue("paiddate", TQVariant(TQDate.currentDate()))
        buffer.setValue("quantity", TQVariant(1))
        return buffer


class ProductPicker(TQComboBox):
    def __init__(self, parent = None, name = None):
        TQComboBox.__init__(self, parent, name)
        cur = TQSqlCursor("prices")
        cur.select(cur.index("id"))
        while cur.next():
            self.insertItem(cur.value("name").toString(), cur.value("id").toInt())


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

    def createEditor(self, parent, field):
        try:
            if str(field.name()) == "pricesid":
                return ProductPicker(parent)
        except AttributeError:
            pass
        return TQSqlEditorFactory.createEditor(self, parent, field)

class Table(CustomTable):
    def __init__(self):
        self.invoiceItemCursor = InvoiceItemCursor()
        TQDataTable.__init__(self, self.invoiceItemCursor)
        self.propMap = TQSqlPropertyMap()
        self.editorFactory = CustomSqlEditorFactory()
        self.propMap.insert("ProductPicker", "pricesid")
        self.installPropertyMap(self.propMap)
        self.installEditorFactory(self.editorFactory)

        for cn, ch in (("pricesid",  "Product"),
                       ("quantity",  "Quantity"),
                       ("price",     "Price" ),
                       ("cost",      "Cost"),
                       ("paiddate",  "Paid")):
            self.addColumn(cn, ch)
        self.setColumnWidth(0 , 150)
        self.setColumnWidth(1, 70)
        self.resize(600, 250)
        self.refresh()


if __name__=='__main__':
    app = TQApplication(sys.argv)
    if createConnection():
        t = Table()
        app.setMainWidget(t)
        t.show()
        app.exec_loop()