OOP in your GUI using GTKmm-3.0 and C++ (Button and Textblock)
From the previous post about setting up environment we build our first graphical user interface with "Hello world" as title, but in this one we will use object-oriented feature in C++ to create our window.
Let's get stated:
From the previous post about setting up environment we build our first graphical user interface with "Hello world" as title, but in this one we will use object-oriented feature in C++ to create our window.
Let's get stated:
- First create a class with Codeblocks in File -> New -> Class and name it "MainWindow".
#ifndef MAINWINDOW_H #define MAINWINDOW_H class MainWindow : public Gtk::Window { public: MainWindow(); virtual ~MainWindow(); protected: }; #endif // MAINWINDOW_H
-
Now second file with the name "MainWindow.cpp" content the body of the function above. Open it an type in the following lines of code.
#include "mainwindow.h" MainWindow::MainWindow(): { set_title("Button and Text"); set_size_request(400,400); } MainWindow::~MainWindow() { //dtor }
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
class MainWindow : public Gtk::Window
{
public:
MainWindow();
virtual ~MainWindow();
protected:
Gtk::Box m_Vbox;
Gtk::ButtonBox myButtonBox;
Gtk::Button left, right;
Gtk::Label textBlock;
};
#endif // MAINWINDOW_H
The variables above are quite self explanatory as in we have two containers, one for holder other element and the other for holding buttons. So here is how the code looks like:
You can download the source code at https://github.com/Bakary-baktech/Gtkmm-3.0-tuto.
#include "mainwindow.h"
MainWindow::MainWindow():
m_Vbox(Gtk::ORIENTATION_VERTICAL), left("Left Button"), right("Right Button")
{
set_title("Button and Text");
set_size_request(400,400);
add(m_Vbox);
m_Vbox.pack_start(textBlock);
m_Vbox.pack_start(myButtonBox);
myButtonBox.pack_start(left);
myButtonBox.pack_start(right);
left.set_margin_left(100);
right.set_margin_right(100);
left.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::left_clicked));
right.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::right_clicked));
show_all_children();
}
MainWindow::~MainWindow()
{
//dtor
}
void MainWindow::left_clicked(){
textBlock.set_text("Left button clicked");
}
void MainWindow::right_clicked()
{
textBlock.set_text("Right button clicked");
}
You can download the source code at https://github.com/Bakary-baktech/Gtkmm-3.0-tuto.
No comments:
Post a Comment