首页 > 解决方案 > 带有图像 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(); 
}

标签: c++imageinterfacegtkgtkmm

解决方案


问题是在调用处理程序后(范围结束),所有局部变量都被销毁,其中包括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自己打电话了。


推荐阅读