文件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() {}
#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() {}
答案 0 :(得分:1)
标签没有显示,因为它在范围的末尾被破坏(即在构造函数的末尾)。 为避免这种情况,您需要在堆上分配Label。但是,为避免内存泄漏,您应该使用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
答案 1 :(得分:1)
You have two problems here. First myLabel2
goes out of scope have the end of your constructor and is destroyed. The second is Gtk::Window
as a single item container and can only hold one widget.
The solution for myLabel2
going out of scope is to allocate it on the heap see @Marcin Kolny answer. Or construct it similar to how you have done with myLabel
.
For the second issue a multi-item container needs to be added to your Gtk::Window
, then you can add your other widgets to that. This container can be a Gtk::Box
, Gtk::Grid
, etc... It depends on your needs.
One of many possible solutions is:
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() {}