我有一个像这样的简单 gtkmm 程序:
文件 main.cpp:
#include "mainwindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
MainWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
文件 mainwindow.h:
#include <gtkmm/window.h>
#include <gtkmm.h>
class MainWindow : public Gtk::Window {
public:
MainWindow();
virtual ~MainWindow();
protected:
Gtk::Label myLabel;
};
和文件 mainwindow.cpp:
#include "mainwindow.h"
#include <iostream>
//using namespace gtk;
MainWindow ::MainWindow():myLabel("this is Label")
{
add(myLabel);
show_all_children();
}
MainWindow::~MainWindow() {}
这段代码运行正常。但是现在我想像这样在文件 mainwindow.cpp 中声明一个标签:
#include "mainwindow.h"
#include <iostream>
MainWindow ::MainWindow():myLabel("this is Label")
{
Gtk::Label myLabel2("this is label 2");
add(myLabel2);
show_all_children();
}
MainWindow::~MainWindow() {}
当我运行这段代码时标签不显示,谁能告诉我哪里出了问题?感谢您的帮助!
最佳答案
标签没有出现,因为它在范围的末尾被销毁(即在构造函数的末尾)。 为了避免这种情况,您需要在堆上分配标签。但是,为了避免内存泄漏,您应该使用 Gtk::manage 函数,这样标签的内存将由容器管理 [1]。
Gtk::Label* myLabel2 = Gtk::manage(new Gtk::Label("this is label 2"));
add(myLabel2);
show_all_children();
[1] https://developer.gnome.org/gtkmm-tutorial/stable/sec-memory-widgets.html.en#memory-managed-dynamic
关于c++ - 如何在文件 .cpp gtkmm 中声明小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42685908/