Menu

Nana Tutorial: Creating A GUI Calculator

Requires: C++11, Nana 0.5(coming soon...)
In this tutorial, we will make a GUI calculator with Nana C++ Library. The calculator that we build will look like:

Screenshot of Calculator

Let's start the code.

:::C++
#include <nana/gui/wvl.hpp>
#include <nana/gui/widgets/button.hpp>
#include <nana/gui/widgets/label.hpp>
#include <nana/gui/place.hpp>

using namepsace nana::gui;

struct stateinfo
{
    enum class state{init, operated, assigned};

    state   opstate;
    wchar_t operation;
    double oprand;
    double outcome;
    label & procedure;
    label & result;

    stateinfo(label& proc, label& resl)
        : opstate(state::init), operation('+'), oprand(0), outcome(0), procedure(proc), result(resl)
    {}
};

void numkey_pressed(stateinfo& state, const eventinfo& ei);
void opkey_pressed(stateinfo& state, const eventinfo& ei);

int main()
{
    form fm;
    fm.caption(STR("Calculator"));

    //use class place to layout the widgets
    place place(fm);
    place.div("vertical<procedure weight=10%><result weight=15%>"
        "<weight=2><<weight=2><opkeys grid [4, 5] gap=2>>");

    label procedure(fm), result(fm);

    //make the label right aligned.
    procedure.text_align(nana::align::right);
    result.text_align(nana::align::right);
    result.typeface(nana::paint::font(nullptr, 14, true));

    place.field("procedure")<<procedure;
    place.field("result")<<result;

    stateinfo state(procedure, result);
    std::vector<std::shared_ptr<button>> op_keys;

    nana::paint::font keyfont(nullptr, 10, true);
    wchar_t keys[] = L"C±%/789X456-123+0.=";
    for(auto i = std::begin(keys), end = std::end(keys); i != end; ++i)
    {
        auto p = std::shared_ptr<button>(new button(fm));
        p->caption(nana::string(1, *i));
        p->typeface(keyfont);
        op_keys.push_back(p);

        if('0' != *i)
        {
            if('=' == *i)
            {
                p->background(0x7ACC);
                p->foreground(0xFFFFFF);
            }
            place.field("opkeys")<<*p<<2;
        }
        else
            place.field("opkeys")<<place.room(*p, 2, 1)<<2;

        //Make event answers for keys
        if(('0' <= *i && *i <= '9') || (*i == '.'))
            p->make_event<events::click>(std::bind(numkey_pressed, std::ref(state), std::placeholders::_1));
        else
            p->make_event<events::click>(std::bind(opkey_pressed, std::ref(state), std::placeholders::_1));
    }

    place.collocate();
    fm.show();
    exec();
}

To get entire code of calculator, please refer to (please wait...)

Posted by Jinhao 2013-03-03 | Draft

Anonymous
Anonymous

Add attachments
Cancel





Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.