associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

CalculadoraQt

Receita: CalculadoraQt

Esta é uma calculadora simples, projetada para ter um comportamento similar às calculadoras de mão.

Foi feita com PyQt e QtDesigner. O código demonstra o uso de um "cache de funções", uma estratégia usada para que possamos utilizar os métodos gerados dinamicamente. Em PyQt especificamente, isto é necessário pois precisamos manter uma referência para todos os métodos dinâmicos (como os gerados com lambda) que forem usados como slots, ou a coleta de lixo irá garantir que não funcionem (o que é normal e esperado, já que as referências para slots são fracas).

O primeiro código é aquele gerado pelo QtDesigner (para quem quiser mexer). O segundo é o código Python gerado via pyuic. O terceiro é uma classe que extende o primeiro, adicionando a ação. O quarto, nosso main().

Obs.: Antes que digam que o código ficou grande, notem que só precisamos mexer com os dois últimos, sendo o último simples e cotidiano. Conhecendo a ferramenta dá pra perceber que o código fica bem econômico e simples de manter.

Código

calcform.ui

   1 <!DOCTYPE UI><UI version="3.3" stdsetdef="1">
   2 <class>CalcForm</class>
   3 <widget class="QWidget">
   4     <property name="name">
   5         <cstring>CalcForm</cstring>
   6     </property>
   7     <property name="geometry">
   8         <rect>
   9             <x>0</x>
  10             <y>0</y>
  11             <width>252</width>
  12             <height>309</height>
  13         </rect>
  14     </property>
  15     <property name="caption">
  16         <string>Calculadora</string>
  17     </property>
  18     <grid>
  19         <property name="name">
  20             <cstring>unnamed</cstring>
  21         </property>
  22         <property name="resizeMode">
  23             <enum>Fixed</enum>
  24         </property>
  25         <widget class="QLineEdit" row="0" column="0" rowspan="1" colspan="4">
  26             <property name="name">
  27                 <cstring>resultEdit</cstring>
  28             </property>
  29             <property name="minimumSize">
  30                 <size>
  31                     <width>0</width>
  32                     <height>45</height>
  33                 </size>
  34             </property>
  35             <property name="font">
  36                 <font>
  37                     <pointsize>14</pointsize>
  38                     <bold>1</bold>
  39                 </font>
  40             </property>
  41             <property name="alignment">
  42                 <set>AlignRight</set>
  43             </property>
  44             <property name="readOnly">
  45                 <bool>true</bool>
  46             </property>
  47             <property name="toolTip" stdset="0">
  48                 <string>Resultados</string>
  49             </property>
  50         </widget>
  51         <widget class="QPushButton" row="1" column="2">
  52             <property name="name">
  53                 <cstring>backspaceButton</cstring>
  54             </property>
  55             <property name="minimumSize">
  56                 <size>
  57                     <width>50</width>
  58                     <height>40</height>
  59                 </size>
  60             </property>
  61             <property name="paletteForegroundColor">
  62                 <color>
  63                     <red>0</red>
  64                     <green>170</green>
  65                     <blue>0</blue>
  66                 </color>
  67             </property>
  68             <property name="font">
  69                 <font>
  70                     <bold>1</bold>
  71                 </font>
  72             </property>
  73             <property name="text">
  74                 <string>B</string>
  75             </property>
  76         </widget>
  77         <widget class="QPushButton" row="5" column="1">
  78             <property name="name">
  79                 <cstring>n0Button</cstring>
  80             </property>
  81             <property name="minimumSize">
  82                 <size>
  83                     <width>50</width>
  84                     <height>40</height>
  85                 </size>
  86             </property>
  87             <property name="font">
  88                 <font>
  89                     <bold>1</bold>
  90                 </font>
  91             </property>
  92             <property name="text">
  93                 <string>0</string>
  94             </property>
  95         </widget>
  96         <widget class="QPushButton" row="4" column="2">
  97             <property name="name">
  98                 <cstring>n3Button</cstring>
  99             </property>
 100             <property name="minimumSize">
 101                 <size>
 102                     <width>50</width>
 103                     <height>40</height>
 104                 </size>
 105             </property>
 106             <property name="font">
 107                 <font>
 108                     <bold>1</bold>
 109                 </font>
 110             </property>
 111             <property name="text">
 112                 <string>3</string>
 113             </property>
 114         </widget>
 115         <widget class="QPushButton" row="4" column="0">
 116             <property name="name">
 117                 <cstring>n1Button</cstring>
 118             </property>
 119             <property name="minimumSize">
 120                 <size>
 121                     <width>50</width>
 122                     <height>40</height>
 123                 </size>
 124             </property>
 125             <property name="font">
 126                 <font>
 127                     <bold>1</bold>
 128                 </font>
 129             </property>
 130             <property name="text">
 131                 <string>1</string>
 132             </property>
 133         </widget>
 134         <widget class="QPushButton" row="2" column="0">
 135             <property name="name">
 136                 <cstring>n7Button</cstring>
 137             </property>
 138             <property name="minimumSize">
 139                 <size>
 140                     <width>50</width>
 141                     <height>40</height>
 142                 </size>
 143             </property>
 144             <property name="font">
 145                 <font>
 146                     <bold>1</bold>
 147                 </font>
 148             </property>
 149             <property name="text">
 150                 <string>7</string>
 151             </property>
 152         </widget>
 153         <widget class="QPushButton" row="1" column="3">
 154             <property name="name">
 155                 <cstring>clearButton</cstring>
 156             </property>
 157             <property name="minimumSize">
 158                 <size>
 159                     <width>50</width>
 160                     <height>40</height>
 161                 </size>
 162             </property>
 163             <property name="paletteForegroundColor">
 164                 <color>
 165                     <red>255</red>
 166                     <green>0</green>
 167                     <blue>0</blue>
 168                 </color>
 169             </property>
 170             <property name="font">
 171                 <font>
 172                     <bold>1</bold>
 173                 </font>
 174             </property>
 175             <property name="text">
 176                 <string>C</string>
 177             </property>
 178         </widget>
 179         <widget class="QPushButton" row="5" column="2">
 180             <property name="name">
 181                 <cstring>calcButton</cstring>
 182             </property>
 183             <property name="minimumSize">
 184                 <size>
 185                     <width>50</width>
 186                     <height>40</height>
 187                 </size>
 188             </property>
 189             <property name="paletteForegroundColor">
 190                 <color>
 191                     <red>0</red>
 192                     <green>0</green>
 193                     <blue>255</blue>
 194                 </color>
 195             </property>
 196             <property name="font">
 197                 <font>
 198                     <bold>1</bold>
 199                 </font>
 200             </property>
 201             <property name="text">
 202                 <string>=</string>
 203             </property>
 204         </widget>
 205         <widget class="QPushButton" row="3" column="3">
 206             <property name="name">
 207                 <cstring>subButton</cstring>
 208             </property>
 209             <property name="minimumSize">
 210                 <size>
 211                     <width>50</width>
 212                     <height>40</height>
 213                 </size>
 214             </property>
 215             <property name="font">
 216                 <font>
 217                     <bold>1</bold>
 218                 </font>
 219             </property>
 220             <property name="text">
 221                 <string>-</string>
 222             </property>
 223         </widget>
 224         <widget class="QPushButton" row="3" column="2">
 225             <property name="name">
 226                 <cstring>n6Button</cstring>
 227             </property>
 228             <property name="minimumSize">
 229                 <size>
 230                     <width>50</width>
 231                     <height>40</height>
 232                 </size>
 233             </property>
 234             <property name="font">
 235                 <font>
 236                     <bold>1</bold>
 237                 </font>
 238             </property>
 239             <property name="text">
 240                 <string>6</string>
 241             </property>
 242         </widget>
 243         <widget class="QPushButton" row="5" column="3">
 244             <property name="name">
 245                 <cstring>divButton</cstring>
 246             </property>
 247             <property name="minimumSize">
 248                 <size>
 249                     <width>50</width>
 250                     <height>40</height>
 251                 </size>
 252             </property>
 253             <property name="font">
 254                 <font>
 255                     <bold>1</bold>
 256                 </font>
 257             </property>
 258             <property name="text">
 259                 <string>/</string>
 260             </property>
 261         </widget>
 262         <widget class="QPushButton" row="3" column="0">
 263             <property name="name">
 264                 <cstring>n4Button</cstring>
 265             </property>
 266             <property name="minimumSize">
 267                 <size>
 268                     <width>50</width>
 269                     <height>40</height>
 270                 </size>
 271             </property>
 272             <property name="font">
 273                 <font>
 274                     <bold>1</bold>
 275                 </font>
 276             </property>
 277             <property name="text">
 278                 <string>4</string>
 279             </property>
 280         </widget>
 281         <widget class="QPushButton" row="2" column="3">
 282             <property name="name">
 283                 <cstring>sumButton</cstring>
 284             </property>
 285             <property name="minimumSize">
 286                 <size>
 287                     <width>50</width>
 288                     <height>40</height>
 289                 </size>
 290             </property>
 291             <property name="font">
 292                 <font>
 293                     <bold>1</bold>
 294                 </font>
 295             </property>
 296             <property name="text">
 297                 <string>+</string>
 298             </property>
 299         </widget>
 300         <widget class="QPushButton" row="4" column="1">
 301             <property name="name">
 302                 <cstring>n2Button</cstring>
 303             </property>
 304             <property name="minimumSize">
 305                 <size>
 306                     <width>50</width>
 307                     <height>40</height>
 308                 </size>
 309             </property>
 310             <property name="font">
 311                 <font>
 312                     <bold>1</bold>
 313                 </font>
 314             </property>
 315             <property name="text">
 316                 <string>2</string>
 317             </property>
 318         </widget>
 319         <widget class="QPushButton" row="3" column="1">
 320             <property name="name">
 321                 <cstring>n5Button</cstring>
 322             </property>
 323             <property name="minimumSize">
 324                 <size>
 325                     <width>50</width>
 326                     <height>40</height>
 327                 </size>
 328             </property>
 329             <property name="font">
 330                 <font>
 331                     <bold>1</bold>
 332                 </font>
 333             </property>
 334             <property name="text">
 335                 <string>5</string>
 336             </property>
 337         </widget>
 338         <widget class="QPushButton" row="4" column="3">
 339             <property name="name">
 340                 <cstring>mulButton</cstring>
 341             </property>
 342             <property name="minimumSize">
 343                 <size>
 344                     <width>50</width>
 345                     <height>40</height>
 346                 </size>
 347             </property>
 348             <property name="font">
 349                 <font>
 350                     <bold>1</bold>
 351                 </font>
 352             </property>
 353             <property name="text">
 354                 <string>X</string>
 355             </property>
 356         </widget>
 357         <widget class="QPushButton" row="2" column="1">
 358             <property name="name">
 359                 <cstring>n8Button</cstring>
 360             </property>
 361             <property name="minimumSize">
 362                 <size>
 363                     <width>50</width>
 364                     <height>40</height>
 365                 </size>
 366             </property>
 367             <property name="font">
 368                 <font>
 369                     <bold>1</bold>
 370                 </font>
 371             </property>
 372             <property name="text">
 373                 <string>8</string>
 374             </property>
 375         </widget>
 376         <widget class="QPushButton" row="2" column="2">
 377             <property name="name">
 378                 <cstring>n9Button</cstring>
 379             </property>
 380             <property name="minimumSize">
 381                 <size>
 382                     <width>50</width>
 383                     <height>40</height>
 384                 </size>
 385             </property>
 386             <property name="font">
 387                 <font>
 388                     <bold>1</bold>
 389                 </font>
 390             </property>
 391             <property name="text">
 392                 <string>9</string>
 393             </property>
 394         </widget>
 395         <widget class="QPushButton" row="5" column="0">
 396             <property name="name">
 397                 <cstring>floatPointButton</cstring>
 398             </property>
 399             <property name="minimumSize">
 400                 <size>
 401                     <width>50</width>
 402                     <height>40</height>
 403                 </size>
 404             </property>
 405             <property name="font">
 406                 <font>
 407                     <bold>1</bold>
 408                 </font>
 409             </property>
 410             <property name="text">
 411                 <string>.</string>
 412             </property>
 413         </widget>
 414     </grid>
 415 </widget>
 416 <tabstops>
 417     <tabstop>resultEdit</tabstop>
 418     <tabstop>backspaceButton</tabstop>
 419     <tabstop>clearButton</tabstop>
 420     <tabstop>n7Button</tabstop>
 421     <tabstop>n8Button</tabstop>
 422     <tabstop>n9Button</tabstop>
 423     <tabstop>sumButton</tabstop>
 424     <tabstop>n4Button</tabstop>
 425     <tabstop>n5Button</tabstop>
 426     <tabstop>n6Button</tabstop>
 427     <tabstop>subButton</tabstop>
 428     <tabstop>n1Button</tabstop>
 429     <tabstop>n2Button</tabstop>
 430     <tabstop>n3Button</tabstop>
 431     <tabstop>mulButton</tabstop>
 432     <tabstop>floatPointButton</tabstop>
 433     <tabstop>n0Button</tabstop>
 434     <tabstop>calcButton</tabstop>
 435     <tabstop>divButton</tabstop>
 436 </tabstops>
 437 <layoutdefaults spacing="6" margin="11"/>
 438 </UI>

calcform.py

   1 # -*- coding: utf-8 -*-
   2 
   3 # Form implementation generated from reading ui file 'calcform.ui'
   4 #
   5 # Created: Seg Set 5 21:17:18 2005
   6 #      by: The PyQt User Interface Compiler (pyuic) 3.13
   7 #
   8 # WARNING! All changes made in this file will be lost!
   9 
  10 
  11 from qt import *
  12 
  13 
  14 class CalcForm(QWidget):
  15     def __init__(self,parent = None,name = None,fl = 0):
  16         QWidget.__init__(self,parent,name,fl)
  17 
  18         if not name:
  19             self.setName("CalcForm")
  20 
  21 
  22         CalcFormLayout = QGridLayout(self,1,1,11,6,"CalcFormLayout")
  23         CalcFormLayout.setResizeMode(QLayout.Fixed)
  24 
  25         self.resultEdit = QLineEdit(self,"resultEdit")
  26         self.resultEdit.setMinimumSize(QSize(0,45))
  27         resultEdit_font = QFont(self.resultEdit.font())
  28         resultEdit_font.setPointSize(14)
  29         resultEdit_font.setBold(1)
  30         self.resultEdit.setFont(resultEdit_font)
  31         self.resultEdit.setAlignment(QLineEdit.AlignRight)
  32         self.resultEdit.setReadOnly(1)
  33 
  34         CalcFormLayout.addMultiCellWidget(self.resultEdit,0,0,0,3)
  35 
  36         self.backspaceButton = QPushButton(self,"backspaceButton")
  37         self.backspaceButton.setMinimumSize(QSize(50,40))
  38         self.backspaceButton.setPaletteForegroundColor(QColor(0,170,0))
  39         backspaceButton_font = QFont(self.backspaceButton.font())
  40         backspaceButton_font.setBold(1)
  41         self.backspaceButton.setFont(backspaceButton_font)
  42 
  43         CalcFormLayout.addWidget(self.backspaceButton,1,2)
  44 
  45         self.n0Button = QPushButton(self,"n0Button")
  46         self.n0Button.setMinimumSize(QSize(50,40))
  47         n0Button_font = QFont(self.n0Button.font())
  48         n0Button_font.setBold(1)
  49         self.n0Button.setFont(n0Button_font)
  50 
  51         CalcFormLayout.addWidget(self.n0Button,5,1)
  52 
  53         self.n3Button = QPushButton(self,"n3Button")
  54         self.n3Button.setMinimumSize(QSize(50,40))
  55         n3Button_font = QFont(self.n3Button.font())
  56         n3Button_font.setBold(1)
  57         self.n3Button.setFont(n3Button_font)
  58 
  59         CalcFormLayout.addWidget(self.n3Button,4,2)
  60 
  61         self.n1Button = QPushButton(self,"n1Button")
  62         self.n1Button.setMinimumSize(QSize(50,40))
  63         n1Button_font = QFont(self.n1Button.font())
  64         n1Button_font.setBold(1)
  65         self.n1Button.setFont(n1Button_font)
  66 
  67         CalcFormLayout.addWidget(self.n1Button,4,0)
  68 
  69         self.n7Button = QPushButton(self,"n7Button")
  70         self.n7Button.setMinimumSize(QSize(50,40))
  71         n7Button_font = QFont(self.n7Button.font())
  72         n7Button_font.setBold(1)
  73         self.n7Button.setFont(n7Button_font)
  74 
  75         CalcFormLayout.addWidget(self.n7Button,2,0)
  76 
  77         self.clearButton = QPushButton(self,"clearButton")
  78         self.clearButton.setMinimumSize(QSize(50,40))
  79         self.clearButton.setPaletteForegroundColor(QColor(255,0,0))
  80         clearButton_font = QFont(self.clearButton.font())
  81         clearButton_font.setBold(1)
  82         self.clearButton.setFont(clearButton_font)
  83 
  84         CalcFormLayout.addWidget(self.clearButton,1,3)
  85 
  86         self.calcButton = QPushButton(self,"calcButton")
  87         self.calcButton.setMinimumSize(QSize(50,40))
  88         self.calcButton.setPaletteForegroundColor(QColor(0,0,255))
  89         calcButton_font = QFont(self.calcButton.font())
  90         calcButton_font.setBold(1)
  91         self.calcButton.setFont(calcButton_font)
  92 
  93         CalcFormLayout.addWidget(self.calcButton,5,2)
  94 
  95         self.subButton = QPushButton(self,"subButton")
  96         self.subButton.setMinimumSize(QSize(50,40))
  97         subButton_font = QFont(self.subButton.font())
  98         subButton_font.setBold(1)
  99         self.subButton.setFont(subButton_font)
 100 
 101         CalcFormLayout.addWidget(self.subButton,3,3)
 102 
 103         self.n6Button = QPushButton(self,"n6Button")
 104         self.n6Button.setMinimumSize(QSize(50,40))
 105         n6Button_font = QFont(self.n6Button.font())
 106         n6Button_font.setBold(1)
 107         self.n6Button.setFont(n6Button_font)
 108 
 109         CalcFormLayout.addWidget(self.n6Button,3,2)
 110 
 111         self.divButton = QPushButton(self,"divButton")
 112         self.divButton.setMinimumSize(QSize(50,40))
 113         divButton_font = QFont(self.divButton.font())
 114         divButton_font.setBold(1)
 115         self.divButton.setFont(divButton_font)
 116 
 117         CalcFormLayout.addWidget(self.divButton,5,3)
 118 
 119         self.n4Button = QPushButton(self,"n4Button")
 120         self.n4Button.setMinimumSize(QSize(50,40))
 121         n4Button_font = QFont(self.n4Button.font())
 122         n4Button_font.setBold(1)
 123         self.n4Button.setFont(n4Button_font)
 124 
 125         CalcFormLayout.addWidget(self.n4Button,3,0)
 126 
 127         self.sumButton = QPushButton(self,"sumButton")
 128         self.sumButton.setMinimumSize(QSize(50,40))
 129         sumButton_font = QFont(self.sumButton.font())
 130         sumButton_font.setBold(1)
 131         self.sumButton.setFont(sumButton_font)
 132 
 133         CalcFormLayout.addWidget(self.sumButton,2,3)
 134 
 135         self.n2Button = QPushButton(self,"n2Button")
 136         self.n2Button.setMinimumSize(QSize(50,40))
 137         n2Button_font = QFont(self.n2Button.font())
 138         n2Button_font.setBold(1)
 139         self.n2Button.setFont(n2Button_font)
 140 
 141         CalcFormLayout.addWidget(self.n2Button,4,1)
 142 
 143         self.n5Button = QPushButton(self,"n5Button")
 144         self.n5Button.setMinimumSize(QSize(50,40))
 145         n5Button_font = QFont(self.n5Button.font())
 146         n5Button_font.setBold(1)
 147         self.n5Button.setFont(n5Button_font)
 148 
 149         CalcFormLayout.addWidget(self.n5Button,3,1)
 150 
 151         self.mulButton = QPushButton(self,"mulButton")
 152         self.mulButton.setMinimumSize(QSize(50,40))
 153         mulButton_font = QFont(self.mulButton.font())
 154         mulButton_font.setBold(1)
 155         self.mulButton.setFont(mulButton_font)
 156 
 157         CalcFormLayout.addWidget(self.mulButton,4,3)
 158 
 159         self.n8Button = QPushButton(self,"n8Button")
 160         self.n8Button.setMinimumSize(QSize(50,40))
 161         n8Button_font = QFont(self.n8Button.font())
 162         n8Button_font.setBold(1)
 163         self.n8Button.setFont(n8Button_font)
 164 
 165         CalcFormLayout.addWidget(self.n8Button,2,1)
 166 
 167         self.n9Button = QPushButton(self,"n9Button")
 168         self.n9Button.setMinimumSize(QSize(50,40))
 169         n9Button_font = QFont(self.n9Button.font())
 170         n9Button_font.setBold(1)
 171         self.n9Button.setFont(n9Button_font)
 172 
 173         CalcFormLayout.addWidget(self.n9Button,2,2)
 174 
 175         self.floatPointButton = QPushButton(self,"floatPointButton")
 176         self.floatPointButton.setMinimumSize(QSize(50,40))
 177         floatPointButton_font = QFont(self.floatPointButton.font())
 178         floatPointButton_font.setBold(1)
 179         self.floatPointButton.setFont(floatPointButton_font)
 180 
 181         CalcFormLayout.addWidget(self.floatPointButton,5,0)
 182 
 183         self.languageChange()
 184 
 185         self.resize(QSize(252,309).expandedTo(self.minimumSizeHint()))
 186         self.clearWState(Qt.WState_Polished)
 187 
 188         self.setTabOrder(self.resultEdit,self.backspaceButton)
 189         self.setTabOrder(self.backspaceButton,self.clearButton)
 190         self.setTabOrder(self.clearButton,self.n7Button)
 191         self.setTabOrder(self.n7Button,self.n8Button)
 192         self.setTabOrder(self.n8Button,self.n9Button)
 193         self.setTabOrder(self.n9Button,self.sumButton)
 194         self.setTabOrder(self.sumButton,self.n4Button)
 195         self.setTabOrder(self.n4Button,self.n5Button)
 196         self.setTabOrder(self.n5Button,self.n6Button)
 197         self.setTabOrder(self.n6Button,self.subButton)
 198         self.setTabOrder(self.subButton,self.n1Button)
 199         self.setTabOrder(self.n1Button,self.n2Button)
 200         self.setTabOrder(self.n2Button,self.n3Button)
 201         self.setTabOrder(self.n3Button,self.mulButton)
 202         self.setTabOrder(self.mulButton,self.floatPointButton)
 203         self.setTabOrder(self.floatPointButton,self.n0Button)
 204         self.setTabOrder(self.n0Button,self.calcButton)
 205         self.setTabOrder(self.calcButton,self.divButton)
 206 
 207 
 208     def languageChange(self):
 209         self.setCaption(self.__tr("Calculadora"))
 210         QToolTip.add(self.resultEdit,self.__tr("Resultados"))
 211         self.backspaceButton.setText(self.__tr("B"))
 212         self.n0Button.setText(self.__tr("0"))
 213         self.n3Button.setText(self.__tr("3"))
 214         self.n1Button.setText(self.__tr("1"))
 215         self.n7Button.setText(self.__tr("7"))
 216         self.clearButton.setText(self.__tr("C"))
 217         self.calcButton.setText(self.__tr("="))
 218         self.subButton.setText(self.__tr("-"))
 219         self.n6Button.setText(self.__tr("6"))
 220         self.divButton.setText(self.__tr("/"))
 221         self.n4Button.setText(self.__tr("4"))
 222         self.sumButton.setText(self.__tr("+"))
 223         self.n2Button.setText(self.__tr("2"))
 224         self.n5Button.setText(self.__tr("5"))
 225         self.mulButton.setText(self.__tr("X"))
 226         self.n8Button.setText(self.__tr("8"))
 227         self.n9Button.setText(self.__tr("9"))
 228         self.floatPointButton.setText(self.__tr("."))
 229 
 230 
 231     def __tr(self,s,c = None):
 232         return qApp.translate("CalcForm",s,c)

calcwidget.py

   1 # -*- coding: iso-8859-1 -*-
   2 
   3 from calcform import CalcForm
   4 import qt
   5 
   6 class CalcWidget(CalcForm):
   7         """Define a janela de calculadora.
   8         """
   9         def __init__(self):
  10                 """Prepara widget.
  11                 """
  12                 super(CalcWidget, self).__init__()
  13                 self.setFocusPolicy(self.StrongFocus)
  14                 self.resultEdit.setFocusPolicy(self.NoFocus)
  15                 # Cache de ações.
  16                 self.action = {}
  17                 self.action[0] = self.__funcAppendToResult('0')
  18                 self.action[1] = self.__funcAppendToResult('1')
  19                 self.action[2] = self.__funcAppendToResult('2')
  20                 self.action[3] = self.__funcAppendToResult('3')
  21                 self.action[4] = self.__funcAppendToResult('4')
  22                 self.action[5] = self.__funcAppendToResult('5')
  23                 self.action[6] = self.__funcAppendToResult('6')
  24                 self.action[7] = self.__funcAppendToResult('7')
  25                 self.action[8] = self.__funcAppendToResult('8')
  26                 self.action[9] = self.__funcAppendToResult('9')
  27                 self.action['+'] = self.__funcDoOperation('+')
  28                 self.action['-'] = self.__funcDoOperation('-')
  29                 self.action['*'] = self.__funcDoOperation('*')
  30                 self.action['/'] = self.__funcDoOperation('/')
  31                 # Conecta ações dos botões numéricos.
  32                 self.connect(self.n0Button, qt.SIGNAL('clicked()'), \
  33                         self.action[0])
  34                 self.connect(self.n1Button, qt.SIGNAL('clicked()'), \
  35                         self.action[1])
  36                 self.connect(self.n2Button, qt.SIGNAL('clicked()'), \
  37                         self.action[2])
  38                 self.connect(self.n3Button, qt.SIGNAL('clicked()'), \
  39                         self.action[3])
  40                 self.connect(self.n4Button, qt.SIGNAL('clicked()'), \
  41                         self.action[4])
  42                 self.connect(self.n5Button, qt.SIGNAL('clicked()'), \
  43                         self.action[5])
  44                 self.connect(self.n6Button, qt.SIGNAL('clicked()'), \
  45                         self.action[6])
  46                 self.connect(self.n7Button, qt.SIGNAL('clicked()'), \
  47                         self.action[7])
  48                 self.connect(self.n8Button, qt.SIGNAL('clicked()'), \
  49                         self.action[8])
  50                 self.connect(self.n9Button, qt.SIGNAL('clicked()'), \
  51                         self.action[9])
  52                 # Botão ponto flutuante.
  53                 self.connect(self.floatPointButton, qt.SIGNAL('clicked()'), \
  54                         self.appendFloatPoint)
  55                 # Botão clear.
  56                 self.connect(self.clearButton, qt.SIGNAL('clicked()'), \
  57                         self.doClear)
  58                 # Botão back.
  59                 self.connect(self.backspaceButton, qt.SIGNAL('clicked()'), \
  60                         self.doBackspace)
  61 
  62                 # Inicializa dados para o cálculo.
  63                 self.doClear()
  64 
  65         def text(self):
  66                 """Retorna texto atual no campo de resultado.
  67                 """
  68                 return str(self.resultEdit.text())
  69 
  70         def setText(self, text):
  71                 """Atribui um novo texto ao campo de resultado.
  72                 """
  73                 self.resultEdit.setText(text)
  74 
  75         def appendText(self, text):
  76                 """Adiciona um texto ao final do campo de resultado.
  77                 """
  78                 self.resultEdit.setText(str(self.resultEdit.text()) + text)
  79 
  80         def doClear(self):
  81                 """Reinicia cálculos.
  82                 """
  83                 # Resultados iniciais.
  84                 self.res = 0
  85                 # Nenhum operador até então.
  86                 self.op = None
  87                 # Ainda sem ponto flutuante.
  88                 self.floatPoint = False
  89                 # Texto inicial.
  90                 self.resultEdit.setText('0')
  91                 # Controla se alguma tecla foi ou não pressionada.
  92                 self.calcKey = False
  93 
  94         def doBackspace(self):
  95                 """Remove o último caractere do campo de texto.
  96                 """
  97                 # Marca ponto flutuante como não usado se excluído.
  98                 if self.text()[-1] == '.':
  99                         self.floatPoint = False
 100                 self.setText(self.text()[:-1])
 101                 # Coloca '0' se o campo estiver vazio.
 102                 if len(self.text()) == 0:
 103                         self.setText('0')
 104 
 105         def doCalc(self):
 106                 """Realiza qualquer cálculo aguardando execução e exibe o resultado.
 107                 """
 108                 # Se a tecla já foi pressionada, ignora.
 109                 if self.calcKey:
 110                         return
 111                 # Captura valor atual.
 112                 current = self.text()
 113                 # Calcula (se houver operação).
 114                 if self.op == None:
 115                         self.res = float(current)
 116                 else:
 117                         try:
 118                                 self.res = eval(str(self.res) + self.op + current)
 119                                 # Exibe resultado.
 120                                 self.setText(str(self.res))
 121                         except ZeroDivisionError:
 122                                 self.doClear()
 123                                 qt.QMessageBox.warning(self, 'Erro', \
 124                                         'Divisão por zero', qt.QMessageBox.Ok)
 125                                 return
 126                 # Marca cálculo como realizado.
 127                 self.op = None
 128                 # Marca tecla pressionada.
 129                 self.calcKey = True
 130 
 131         def __funcAppendToResult(self, s):
 132                 """Gera um método que adiciona a string especificada ao campo
 133                 de resultado.
 134                 """
 135                 def appendToResult():
 136                         # Remove o '0' inicial.
 137                         # Verifica se está iniciando uma nova operação.
 138                         if self.text() != '0' and not self.calcKey:
 139                                 self.appendText(s)
 140                         else:
 141                                 self.setText(s)
 142                         # Marca tecla como pressionada.
 143                         self.calcKey = False
 144                 return appendToResult
 145 
 146         def __funcDoOperation(self, op):
 147                 """Gera um método que realiza a operação especificada.
 148                 """
 149                 def doOperation():
 150                         self.doCalc()
 151                         self.op = op
 152                 return doOperation
 153 
 154         def appendFloatPoint(self):
 155                 """Adiciona um caractere de ponto flutuante ao campo de resultado.
 156 
 157                 Caso já exista um ponto, ignora.
 158                 """
 159                 # Verifica se está iniciando uma nova operação.
 160                 if self.op:
 161                         self.setText('0.')
 162                         # Reinicia operador.
 163                         self.op = None
 164                 if not self.floatPoint:
 165                         self.appendText('.')
 166                 self.floatPoint = True
 167 
 168         def keyPressEvent(self, evt):
 169                 """Evento disparado ao receber eventos do teclado.
 170                 """
 171                 # Números.
 172                 if evt.text() == '0':
 173                         self.action[0]()
 174                 elif evt.text() == '1':
 175                         self.action[1]()
 176                 elif evt.text() == '2':
 177                         self.action[2]()
 178                 elif evt.text() == '3':
 179                         self.action[3]()
 180                 elif evt.text() == '4':
 181                         self.action[4]()
 182                 elif evt.text() == '5':
 183                         self.action[5]()
 184                 elif evt.text() == '6':
 185                         self.action[6]()
 186                 elif evt.text() == '7':
 187                         self.action[7]()
 188                 elif evt.text() == '8':
 189                         self.action[8]()
 190                 elif evt.text() == '9':
 191                         self.action[9]()
 192                 # Ponto flutuante.
 193                 elif evt.text() == '.':
 194                         self.appendFloatPoint()
 195                 # Clear.
 196                 elif evt.key() == self.Key_Escape:
 197                         self.doClear()
 198                 # Backspace.
 199                 elif evt.key() == self.Key_Backspace:
 200                         self.doBackspace()
 201                 # Return e Enter (o 2° do teclado numérico)
 202                 elif evt.key() == self.Key_Return or evt.key() == self.Key_Enter:
 203                         self.doCalc()
 204                 # Operações matemáticas.
 205                 elif evt.text() == '+':
 206                         self.action['+']()
 207                 elif evt.text() == '-':
 208                         self.action['-']()
 209                 elif evt.text() == '*':
 210                         self.action['*']()
 211                 elif evt.text() == '/':
 212                         self.action['/']()
 213                 # Passa evento para que uma camada superior interprete.
 214                 else:
 215                         evt.ignore()

calc.py

   1 # -*- coding: iso-8859-1 -*-
   2 
   3 import sys, qt
   4 import calcwidget
   5 
   6 import calcform
   7 
   8 class Calc(qt.QApplication):
   9         """Define uma aplicação de calculadora.
  10         """
  11         def __init__(self, argv):
  12                 """Prepara e executa aplicação, a partir dos argumentos de linha de
  13                 comando passados.
  14                 """
  15                 super(Calc, self).__init__(argv)
  16                 mainWidget = calcwidget.CalcWidget()
  17                 self.setMainWidget(mainWidget)
  18                 mainWidget.show()
  19                 self.exec_loop()
  20 
  21 
  22 def main():
  23         Calc(sys.argv)
  24 
  25 if __name__ == '__main__':
  26         main()

Volta para CookBook.


JoaoPauloSilva