如何在文件.cpp gtkmm中声明小部件
How to declared widget in file .cpp gtkmm
我有一个简单的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::Box
,Gtk::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() {}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 最小硬币更换问题(自上而下方法)
- Qt VTK交互风格的信号到小部件
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 如何在Qt窗口小部件中使用QStringView(或QStringRef)
- 使用递归的数组的最小值.这是怎么回事
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 为什么在浮点中从大到小会引入更多的误差
- 如何在文件.cpp gtkmm中声明小部件
- C++ 创建小部件数组
- Qt:在c++类中有一个未声明为指针的小部件字段是很好的
- 使用更小的函数来分解长方法-正确的风格/如何声明
- 将枚举(在结构体内部声明的)值赋给结构体内部相同枚举类型的变量