c++ - 带有图像 GTK C++ 的窗口
问题描述
我正在尝试通过单击按钮从现有窗口打开一个新窗口。新窗口应显示图像。当我单击按钮时,会显示新窗口,但不显示图像。没有错误。
我确保我的图像在当前目录中并且是可读的。怎么了?
代码:
void ExampleWindow::on_button_clicked()
{
std::cout << "The Button was clicked." << std::endl;
Gtk::Window *window = new Gtk::Window();
Gtk::VBox mainLayout;
window->add(mainLayout);
Gtk::Image image("Vampire.png");
mainLayout.pack_start(image);
window->show_all();
}
解决方案
问题是在调用处理程序后(范围结束),所有局部变量都被销毁,其中包括image
.
这是有效的代码:
#include <iostream>
#include <memory>
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow()
: m_image("Vampire.png")
{
add(m_btn);
m_btn.signal_clicked().connect([this](){OnButtonClicked();});
}
private:
void OnButtonClicked()
{
std::cout << __FUNCTION__ << " enter scope" << std::endl;
m_window = std::make_unique<Gtk::Window>();
m_window->add(m_image);
m_window->show_all();
std::cout << __FUNCTION__ << " leaving scope" << std::endl;
// With your code, image is destroyed here. The window still
// lives because it was newed, but you lost your reference to
// it and so the program will leak memory (i.e. you will be
// unable to call delete on it, unless it is a class member).
}
Gtk::Button m_btn("Show image");
Gtk::Image m_image;
std::unique_ptr<Gtk::Window> m_window;
};
int main(int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "so.question.q65011763");
ExampleWindow window;
window.show_all();
return app->run(window);
// With this code, the image and the window are both destroyed here.
// Since the window is in a unique_ptr, delete will be automatically
// called on it.
}
请注意,我已将所有变量设为类成员,以便它们在处理程序的范围结束后存活。我还将包含图像的窗口存储在智能指针中,这样我就不必delete
自己打电话了。
推荐阅读
- c# - 如何使用此代码使我的角色双跳?(新手)
- android - 是否可以将 React Native UI 组件导入原生(Android/iOS)项目?
- react-native - 如何使用 mapDispatchToProps 代替直接访问 Redux 存储?
- javascript - 拆分参数的问题(Discord Bot)
- amazon-web-services - API Gateway 自定义授权人之谜 503
- algorithm - Python中的并行快速排序
- ruby-on-rails - 在 Ruby on Rails 应用程序中生成视图所需的 Json 时 Heroku 超时
- ruby-on-rails - Capistrano 无法读取 ENV 变量
- json - 贾斯珀报告。在子表中使用来自父 json 的值
- java - 如何在二维字符数组中查找字符频率?