在 vala Gtk4 中用另一个可绘制对象替换

问题描述 投票:0回答:1

我想让我的应用程序在使用

Gtk4
单击按钮时将图像更改为另一个应用程序。

 public class Main : Object
{
    public static int main()
    {
        var app = new Gtk.Application ("example.com.Demo", ApplicationFlags.FLAGS_NONE);

        app.activate.connect
        (() => {
            var window = new Gtk.ApplicationWindow(app);

            var image = new Gtk.Picture.for_filename("img1.jpg");
            var button = new Gtk.Button.with_label("Change Image");
            button.clicked.connect(
                // how to change the image
            );

            var box = new Gtk.Box(Gtk.Orientation.VERTICAL, 10);
            box.append(image);
            box.append(button);

            window.set_child(box);
            window.present();
            image.show();
        });
        return app.run();
    }
}

我尝试使用

Gtk.Image()
和方法
image.set_from_paintable
失败并出现错误:

: error: Argument 1: Cannot convert from `Gtk.Picture' to `unowned Gdk.Paintable?'
   29 |                 image.set_paintable(new Gtk.Picture.for_filename("img2.jpg"));

我还尝试过使用容器

var box = new Gtk.Box(...)
删除一个
Gtk.Picture
并附加第二个,但我无法工作。

vala gtk4
1个回答
0
投票

有效的方法是首先声明两张图片,然后使用容器删除图像并附加第二张图片:

 public class Main : Object
{
    public static int main()
    {
        var app = new Gtk.Application ("example.com.Demo", ApplicationFlags.FLAGS_NONE);

        app.activate.connect
        (() => {
            var window = new Gtk.ApplicationWindow(app);

            var image1 = new Gtk.Picture.for_filename("img1.jpg");
            var image2 = new Gtk.Picture.for_filename("img2.jpg");

            var container = new Gtk.Box(Gtk.Orientation.Vertical, 10);
            container.append(image1);

            var button = new Gtk.Button.with_label("Change Image");
            button.clicked.connect(
                container.remove(image1);
                container.append(image2);
            );

            var box = new Gtk.Box(Gtk.Orientation.VERTICAL, 10);
            box.append(image);
            box.append(button);

            window.set_child(box);
            window.present();
            image.show();
        });
        return app.run();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.