0

我有一个像这样的简单 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() {}

运行此代码时标签不显示,有人可以告诉我什么问题吗?感谢您的帮助!

4

2 回答 2

1

你这里有两个问题。首先myLabel2超出范围,构造函数结束并被销毁。第二种是Gtk::Window作为单个项目容器,只能容纳一个小部件。

myLabel2超出范围的解决方案是在堆上分配它,请参阅@Marcin Kolny 回答。或者按照您对myLabel.

对于第二个问题,需要将多项目容器添加到您的Gtk::Window中,然后您可以将其他小部件添加到其中。这个容器可以是Gtk::Box, Gtk::Grid, 等等...这取决于你的需要。

许多可能的解决方案之一是:

主窗口.h

#include <gtkmm.h>

class MainWindow : public Gtk::Window {
public:
    MainWindow();
    virtual ~MainWindow();
protected:
    Gtk::Box myBox;
    Gtk::Label myLabel;
    Gtk::Label myLabel2;
};

主窗口.cpp

#include "mainwindow.h"

MainWindow::MainWindow():
  myLabel("this is Label"), myLabel2("this is label 2");
{
  add myBox;
  myBox.pack_start(myLabel);
  myBox.pack_start(myLabel2);
  show_all_children();
}
MainWindow::~MainWindow() {}
于 2017-03-09T08:36:23.277 回答
1

标签没有显示出来,因为它在作用域的末尾被销毁(即在构造函数的末尾)。为避免这种情况,您需要在堆上分配标签。但是,为避免内存泄漏,您应该使用 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

于 2017-03-09T07:20:43.947 回答