Button based calculator : QPushButton « Qt « C++

Home
C++
1.Bitset
2.Class
3.Console
4.Data Structure
5.Data Type
6.Deque
7.Development
8.File
9.Function
10.Generic
11.Language
12.List
13.Map Multimap
14.Overload
15.Pointer
16.Qt
17.Queue Stack
18.Set Multiset
19.STL Algorithms Binary search
20.STL Algorithms Heap
21.STL Algorithms Helper
22.STL Algorithms Iterator
23.STL Algorithms Merge
24.STL Algorithms Min Max
25.STL Algorithms Modifying sequence operations
26.STL Algorithms Non modifying sequence operations
27.STL Algorithms Sorting
28.STL Basics
29.String
30.Valarray
31.Vector
C / ANSI-C
C Tutorial
C++ Tutorial
Visual C++ .NET
C++ » Qt » QPushButtonScreenshots 
Button based calculator
  

/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef CALCULATOR_H
#define CALCULATOR_H

#include <QDialog>

QT_BEGIN_NAMESPACE
class QLineEdit;
QT_END_NAMESPACE
class Button;


class Calculator : public QDialog
{
    Q_OBJECT

public:
    Calculator(QWidget *parent = 0);

private slots:
    void digitClicked();
    void unaryOperatorClicked();
    void additiveOperatorClicked();
    void multiplicativeOperatorClicked();
    void equalClicked();
    void pointClicked();
    void changeSignClicked();
    void backspaceClicked();
    void clear();
    void clearAll();
    void clearMemory();
    void readMemory();
    void setMemory();
    void addToMemory();



private:
 
    Button *createButton(const QString &text, const char *member);
    void abortOperation();
    bool calculate(double rightOperand, const QString &pendingOperator);



    double sumInMemory;
 
    double sumSoFar;
 
    double factorSoFar;
 
    QString pendingAdditiveOperator;
 
    QString pendingMultiplicativeOperator;
 
    bool waitingForOperand;



    QLineEdit *display;
 

    enum NumDigitButtons = 10 };
    Button *digitButtons[NumDigitButtons];
};


#endif




#include <QtGui>

#include <math.h>

#include "button.h"
#include "calculator.h"


Calculator::Calculator(QWidget *parent)
    : QDialog(parent)
{
    sumInMemory = 0.0;
    sumSoFar = 0.0;
    factorSoFar = 0.0;
    waitingForOperand = true;



    display = new QLineEdit("0");
 
    display->setReadOnly(true);
    display->setAlignment(Qt::AlignRight);
    display->setMaxLength(15);

    QFont font = display->font();
    font.setPointSize(font.pointSize() 8);
    display->setFont(font);



    for (int i = 0; i < NumDigitButtons; ++i) {
  digitButtons[i= createButton(QString::number(i), SLOT(digitClicked()));
    }

    Button *pointButton = createButton(tr("."), SLOT(pointClicked()));
    Button *changeSignButton = createButton(tr("\261"), SLOT(changeSignClicked()));

    Button *backspaceButton = createButton(tr("Backspace"), SLOT(backspaceClicked()));
    Button *clearButton = createButton(tr("Clear"), SLOT(clear()));
    Button *clearAllButton = createButton(tr("Clear All"), SLOT(clearAll()));

    Button *clearMemoryButton = createButton(tr("MC"), SLOT(clearMemory()));
    Button *readMemoryButton = createButton(tr("MR"), SLOT(readMemory()));
    Button *setMemoryButton = createButton(tr("MS"), SLOT(setMemory()));
    Button *addToMemoryButton = createButton(tr("M+"), SLOT(addToMemory()));

    Button *divisionButton = createButton(tr("\367"), SLOT(multiplicativeOperatorClicked()));
    Button *timesButton = createButton(tr("\327"), SLOT(multiplicativeOperatorClicked()));
    Button *minusButton = createButton(tr("-"), SLOT(additiveOperatorClicked()));
    Button *plusButton = createButton(tr("+"), SLOT(additiveOperatorClicked()));

    Button *squareRootButton = createButton(tr("Sqrt"), SLOT(unaryOperatorClicked()));
    Button *powerButton = createButton(tr("x\262"), SLOT(unaryOperatorClicked()));
    Button *reciprocalButton = createButton(tr("1/x"), SLOT(unaryOperatorClicked()));
    Button *equalButton = createButton(tr("="), SLOT(equalClicked()));



    QGridLayout *mainLayout = new QGridLayout;
 
    mainLayout->setSizeConstraint(QLayout::SetFixedSize);

    mainLayout->addWidget(display, 0016);
    mainLayout->addWidget(backspaceButton, 1012);
    mainLayout->addWidget(clearButton, 1212);
    mainLayout->addWidget(clearAllButton, 1412);

    mainLayout->addWidget(clearMemoryButton, 20);
    mainLayout->addWidget(readMemoryButton, 30);
    mainLayout->addWidget(setMemoryButton, 40);
    mainLayout->addWidget(addToMemoryButton, 50);

    for (int i = 1; i < NumDigitButtons; ++i) {
        int row = ((- i32;
        int column = ((i - 131;
        mainLayout->addWidget(digitButtons[i], row, column);
    }

    mainLayout->addWidget(digitButtons[0]51);
    mainLayout->addWidget(pointButton, 52);
    mainLayout->addWidget(changeSignButton, 53);

    mainLayout->addWidget(divisionButton, 24);
    mainLayout->addWidget(timesButton, 34);
    mainLayout->addWidget(minusButton, 44);
    mainLayout->addWidget(plusButton, 54);

    mainLayout->addWidget(squareRootButton, 25);
    mainLayout->addWidget(powerButton, 35);
    mainLayout->addWidget(reciprocalButton, 45);
    mainLayout->addWidget(equalButton, 55);
    setLayout(mainLayout);

    setWindowTitle(tr("Calculator"));
}



void Calculator::digitClicked()
{
    Button *clickedButton = qobject_cast<Button *>(sender());
    int digitValue = clickedButton->text().toInt();
    if (display->text() == "0" && digitValue == 0.0)
        return;

    if (waitingForOperand) {
        display->clear();
  waitingForOperand = false;
    }
    display->setText(display->text() + QString::number(digitValue));
}



void Calculator::unaryOperatorClicked()
 
{
    Button *clickedButton = qobject_cast<Button *>(sender());
    QString clickedOperator = clickedButton->text();
    double operand = display->text().toDouble();
    double result = 0.0;

    if (clickedOperator == tr("Sqrt")) {
        if (operand < 0.0) {
            abortOperation();
            return;
        }
        result = sqrt(operand);
    else if (clickedOperator == tr("x\262")) {
        result = pow(operand, 2.0);
    else if (clickedOperator == tr("1/x")) {
        if (operand == 0.0) {
      abortOperation();
      return;
        }
        result = 1.0 / operand;
    }
    display->setText(QString::number(result));
    waitingForOperand = true;
}



void Calculator::additiveOperatorClicked()
 
{
    Button *clickedButton = qobject_cast<Button *>(sender());
    QString clickedOperator = clickedButton->text();
    double operand = display->text().toDouble();

 
    if (!pendingMultiplicativeOperator.isEmpty()) {
 
        if (!calculate(operand, pendingMultiplicativeOperator)) {
            abortOperation();
      return;
        }
        display->setText(QString::number(factorSoFar));
        operand = factorSoFar;
        factorSoFar = 0.0;
        pendingMultiplicativeOperator.clear();
    }

 
    if (!pendingAdditiveOperator.isEmpty()) {
 
        if (!calculate(operand, pendingAdditiveOperator)) {
            abortOperation();
      return;
        }
        display->setText(QString::number(sumSoFar));
    else {
        sumSoFar = operand;
    }

 
    pendingAdditiveOperator = clickedOperator;
 
    waitingForOperand = true;
}



void Calculator::multiplicativeOperatorClicked()
{
    Button *clickedButton = qobject_cast<Button *>(sender());
    QString clickedOperator = clickedButton->text();
    double operand = display->text().toDouble();

    if (!pendingMultiplicativeOperator.isEmpty()) {
        if (!calculate(operand, pendingMultiplicativeOperator)) {
            abortOperation();
      return;
        }
        display->setText(QString::number(factorSoFar));
    else {
        factorSoFar = operand;
    }

    pendingMultiplicativeOperator = clickedOperator;
    waitingForOperand = true;
}



void Calculator::equalClicked()
{
    double operand = display->text().toDouble();

    if (!pendingMultiplicativeOperator.isEmpty()) {
        if (!calculate(operand, pendingMultiplicativeOperator)) {
            abortOperation();
      return;
        }
        operand = factorSoFar;
        factorSoFar = 0.0;
        pendingMultiplicativeOperator.clear();
    }
    if (!pendingAdditiveOperator.isEmpty()) {
        if (!calculate(operand, pendingAdditiveOperator)) {
            abortOperation();
      return;
        }
        pendingAdditiveOperator.clear();
    else {
        sumSoFar = operand;
    }

    display->setText(QString::number(sumSoFar));
    sumSoFar = 0.0;
    waitingForOperand = true;
}



void Calculator::pointClicked()
{
    if (waitingForOperand)
        display->setText("0");
    if (!display->text().contains("."))
        display->setText(display->text() + tr("."));
    waitingForOperand = false;
}



void Calculator::changeSignClicked()
{
    QString text = display->text();
    double value = text.toDouble();

    if (value > 0.0) {
        text.prepend(tr("-"));
    else if (value < 0.0) {
        text.remove(01);
    }
    display->setText(text);
}



void Calculator::backspaceClicked()
{
    if (waitingForOperand)
        return;

    QString text = display->text();
    text.chop(1);
    if (text.isEmpty()) {
        text = "0";
        waitingForOperand = true;
    }
    display->setText(text);
}



void Calculator::clear()
{
    if (waitingForOperand)
        return;

    display->setText("0");
    waitingForOperand = true;
}



void Calculator::clearAll()
{
    sumSoFar = 0.0;
    factorSoFar = 0.0;
    pendingAdditiveOperator.clear();
    pendingMultiplicativeOperator.clear();
    display->setText("0");
    waitingForOperand = true;
}



void Calculator::clearMemory()
{
    sumInMemory = 0.0;
}

void Calculator::readMemory()
{
    display->setText(QString::number(sumInMemory));
    waitingForOperand = true;
}

void Calculator::setMemory()
{
    equalClicked();
    sumInMemory = display->text().toDouble();
}

void Calculator::addToMemory()
{
    equalClicked();
    sumInMemory += display->text().toDouble();
}


Button *Calculator::createButton(const QString &text, const char *member)
{
    Button *button = new Button(text);
    connect(button, SIGNAL(clicked()), this, member);
    return button;
}



void Calculator::abortOperation()
{
    clearAll();
    display->setText(tr("####"));
}



bool Calculator::calculate(double rightOperand, const QString &pendingOperator)
{
    if (pendingOperator == tr("+")) {
        sumSoFar += rightOperand;
    else if (pendingOperator == tr("-")) {
        sumSoFar -= rightOperand;
    else if (pendingOperator == tr("\327")) {
        factorSoFar *= rightOperand;
    else if (pendingOperator == tr("\367")) {
  if (rightOperand == 0.0)
      return false;
  factorSoFar /= rightOperand;
    }
    return true;
}







#ifndef BUTTON_H
#define BUTTON_H

#include <QToolButton>


class Button : public QToolButton
{
    Q_OBJECT

public:
    Button(const QString &text, QWidget *parent = 0);

    QSize sizeHint() const;
};


#endif





#include <QtGui> 

#include "button.h"


Button::Button(const QString &text, QWidget *parent)
    : QToolButton(parent)
{
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    setText(text);
}



QSize Button::sizeHint() const
 
{
    QSize size = QToolButton::sizeHint();
    size.rheight() += 20;
    size.rwidth() = qMax(size.width(), size.height());
    return size;
}





#include <QApplication>

#include "calculator.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Calculator calc;
    calc.show();
    return app.exec();
}

   
    
  
Related examples in the same category
1.Add clicked event for push button
2.Create PushButton and add to window
3.Calculator with push buttons
4.extends QPushButton
5.toggle button demo
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.