【发布时间】:2021-02-10 15:55:25
【问题描述】:
我正在尝试学习如何使用 gtkmm,已经基本掌握了 C++(我喜欢挑战!)。我一直在学习教程(以及其他阅读)。我正在尝试使用 glade 的方法来设计 UI,然后编写代码来完成工作。
所以我构建了一个非常简单的 UI(目前是窗口和按钮!)。我正在使用 GTK::Builder 从文件中加载 UI。我将代码分为类和主调用者。
这里是main.cpp
#include "hellowindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[]) {
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example"); //creates a Gtk::Application object, stored in a Glib::RefPtr smartpointer, create() method for this object initializes gtkmm.
HelloWindow hw; // Create a HelloWindow object
return app->run(hw, argc, argv); // shows the HelloWindow object and enter the gtkmm main processing loop, will then return with an appropriate success or error code
}
这是 HelloWindow 类的标题
#ifndef HELLOWINDOW_H
#define HELLOWINDOW_H
#include <gtkmm/application.h>
#include <gtkmm/applicationwindow.h>
#include <gtkmm/button.h>
#include <gtkmm/box.h>
#include <gtkmm/builder.h>
#include <glibmm/fileutils.h>
/* derive the class from Gtk::ApplicationWindow base class */
class HelloWindow : public Gtk::ApplicationWindow {
public:
/* Conctructor */
HelloWindow();
/* Destructor */
~HelloWindow() override;
protected:
/* Signal handlers: */
void on_button_clicked();
/* Member widgets: */
Gtk::Box *cont; // Container
Gtk::Button *pButton; // Pointer to a Button
Glib::RefPtr<Gtk::Button> display_btn; // Smart pointer to a Button
Glib::RefPtr<Gtk::Builder> builder; // Builder
};
#endif // HELLOWINDOW_H
这是课程代码:
#include "hellowindow.h"
#include <iostream>
HelloWindow::HelloWindow() : builder(Gtk::Builder::create()){
try {
/* load window from glade file */
builder->add_from_file("glade/simple.glade");
}
catch(const Glib::FileError& ex) {
/* catch file errors */
std::cerr << "FileError: " << ex.what() << std::endl;
return;
}
/* ui builder created successfully from file */
/* add a container to the builder */
builder->get_widget<Gtk::Box>("cont", cont);
builder->get_widget<Gtk::Button>("display_button", pButton);
pButton->signal_clicked().connect(
sigc::mem_fun(*this, &HelloWindow::on_button_clicked)
);
/* add the container to the application window */
add(*cont);
/* set some parameters for the window */
set_title("Simple Gtk::Builder Demo"); // set the window title
set_default_size(500, 500); // set the window size
show_all(); // show the window and all of the enclosed widgets
}
HelloWindow::~HelloWindow(){
}
void HelloWindow::on_button_clicked(){
std::cout << "Hello World" << std::endl;
}
这一切都很好,我想我明白发生了什么。但是,我看到了一种在运行时添加小部件的不同方法 (https://sodocumentation.net/gtk3/topic/5579/using-glade-with-builder-api)。不同之处在于按钮对象的声明方式。在上面的代码中,它被声明为指向按钮对象的指针:
builder->get_widget<Gtk::Button>("display_button", pButton);
但是,上面的网站使用智能指针指向按钮对象的方法:
display_btn = Glib::RefPtr<Gtk::Button>::cast_dynamic(builder->get_object("display_button"));
第二种方法似乎不太清楚,特别是 cast_dynamic 方面,有人能解释一下这两种方法之间的区别吗?
我希望我已经包含了足够的信息。
谢谢
马丁
【问题讨论】:
标签: c++ memory-management smart-pointers gtkmm