如何在文件.cpp gtkmm中声明小部件

How to declared widget in file .cpp gtkmm

本文关键字:声明 小部 gtkmm cpp 文件      更新时间:2023-10-16

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

此代码运行正常。但是现在我想在file 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 ::管理功能,因此标签的内存将由容器[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-manated-dynamic

您在这里有两个问题。首先,myLabel2超出范围的结束,并被摧毁。第二个是Gtk::Window作为单个项目容器,只能容纳一个小部件。

myLabel2出现范围的解决方案是在堆上分配@marcin Kolny答案。或类似于您对myLabel的方式类似。

在第二期中,需要将多项目容器添加到您的Gtk::Window中,然后您可以将其他小部件添加到其中。该容器可以是Gtk::BoxGtk::Grid等...这取决于您的需求。

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

mainWindow.h

#include <gtkmm.h>
class MainWindow : public Gtk::Window {
public:
    MainWindow();
    virtual ~MainWindow();
protected:
    Gtk::Box myBox;
    Gtk::Label myLabel;
    Gtk::Label myLabel2;
};

mainwindow.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() {}