GTK 3 警告,要求“先把控件移出现有容器”,如何解决?

我用 glade 创建了一个 GtkWindow,在里面放了一个 GtkFixed,在这个 Fixed 里又放了一个 label 和一个 button。

// demo.cpp
#include <gtkmm/application.h>
#include <gtkmm/window.h>
#include <gtkmm/applicationwindow.h>
#include <gtkmm/button.h>
#include <gtkmm/label.h>
#include <gtkmm/box.h>
#include <gtkmm/fixed.h>
#include <gtkmm/builder.h>

class HelloWindow : public Gtk::Window {
    Gtk::Fixed *fixed_1;
    Glib::RefPtr<Gtk::Label> label_1;
    Glib::RefPtr<Gtk::Button> button_1;
    Glib::RefPtr<Gtk::Builder> ui;
public:
    HelloWindow()
    : ui{Gtk::Builder::create_from_file("demo.glade")} {
        if(ui) {
            ui->get_widget<Gtk::Fixed>("fixed_1", fixed_1);
            label_1 = Glib::RefPtr<Gtk::Label>::cast_dynamic(
                ui->get_object("label_1")
            );
            button_1 = Glib::RefPtr<Gtk::Button>::cast_dynamic(
                ui->get_object("button_1")
            );
            if(fixed_1 && label_1 && button_1) {
                button_1->signal_clicked().connect(
                [this]() {
                    label_1->set_text("Hello GTKmm");
                });
                add(*fixed_1);
            }
        }
        set_title("Simple Gtk::Builder demo");
        set_default_size(400, 400);
        show_all();
    }
};

int main(int argc, char *argv[]) {
    auto app = Gtk::Application::create(
        argc, argv,
        "org.gtkmm.example.HelloApp"
    );
    HelloWindow hw;
    return app->run(hw);
}

编译运行后报错

(a.out:71203): Gtk-WARNING **: 18:03:11.173: Attempting to add a widget with type gtkmm__GtkFixed to a container of type gtkmm__GtkWindow, but the widget is already inside a container of type gtkmm__GtkWindow, please remove the widget from its existing container first.
阅读 1.9k
1 个回答

试试这样,手上没有什么环境,不能帮你调试,但是我记得还要套一层才可以的

class HelloWindow : public Gtk::Window {
    Gtk::Box box;
    Gtk::Fixed *fixed_1;
    Glib::RefPtr<Gtk::Label> label_1;
    Glib::RefPtr<Gtk::Button> button_1;
    Glib::RefPtr<Gtk::Builder> ui;
public:
    HelloWindow()
    : box(Gtk::ORIENTATION_VERTICAL), ui{Gtk::Builder::create_from_file("demo.glade")} {
        if(ui) {
            ui->get_widget<Gtk::Fixed>("fixed_1", fixed_1);
            label_1 = Glib::RefPtr<Gtk::Label>::cast_dynamic(
                ui->get_object("label_1")
            );
            button_1 = Glib::RefPtr<Gtk::Button>::cast_dynamic(
                ui->get_object("button_1")
            );
            if(fixed_1 && label_1 && button_1) {
                button_1->signal_clicked().connect(
                [this]() {
                    label_1->set_text("Hello GTKmm");
                });
                box.add(*fixed_1);
                add(box);
            }
        }
        set_title("Simple Gtk::Builder demo");
        set_default_size(400, 400);
        show_all();
    }
};
本文参与了SegmentFault 思否面试闯关挑战赛,欢迎正在阅读的你也加入。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏