首页 > 解决方案 > 在 Gtk::Grid 中移动 Gtk::Widget 的位置

问题描述

我想在网格内移动两个小部件的位置。我该怎么做?到目前为止我得到了什么:

        pWidget1->unparent();
        pWidget2->unparent();

        pGrid->attach(*(pWidget1), 0, 5);
        pGrid->attach(*(pWidget2), 0, 7);
        show_all();

可悲的是,这段代码没有做我想要的:小部件的位置没有改变。

标签: c++gtkmmgtkmm3

解决方案


下面的例子是用 Gtkmm 3.24 编写的,它创建了一个窗口,其中三个按钮在Gtk::Grid. 单击“切换”按钮将交换网格内的AB。这里的关键思想是

  1. Gtk::Grid::remove要移动的小部件。
  2. Gtk::Grid::attach他们到他们的新位置。

这是代码:

#include <iostream>
#include <gtkmm.h>

class MainWindow : public Gtk::Window
{

public:

    MainWindow()
    {
        // Set buttons up:
        m_btnA.set_label("A");
        m_btnB.set_label("B");

        m_btnSwitch.set_label("Switch A and B");
        m_btnSwitch.signal_clicked().connect([this](){OnSwitch();});

        // Populate grid (initial layout):
        m_grid.attach(m_btnA, 0, 0, 1, 1);
        m_grid.attach(m_btnB, 1, 0, 1, 1);
        m_grid.attach(m_btnSwitch, 0, 1, 2, 1);

        // Set window up:
        add(m_grid);
        show_all();
    }

private:

    void OnSwitch()
    {
        std::cout << "Switching A and B in grid..." << std::endl;

        // First, remove the buttons from the grid:
        m_grid.remove(m_btnA);
        m_grid.remove(m_btnB);

        // Then, re-add them in reverse order:
        if(m_aBtnFirst)
        {
            // Make "A" the second button:
            m_grid.attach(m_btnA, 1, 0, 1, 1);
            m_grid.attach(m_btnB, 0, 0, 1, 1);
        }
        else
        {
            // Make "A" the first button:
            m_grid.attach(m_btnA, 0, 0, 1, 1);
            m_grid.attach(m_btnB, 1, 0, 1, 1);
        }

        // Update state:
        m_aBtnFirst = !m_aBtnFirst;

    }

    Gtk::Grid m_grid;
    Gtk::Button m_btnA;
    Gtk::Button m_btnB;

    Gtk::Button m_btnSwitch;

    bool m_aBtnFirst = true;

};

int main(int argc, char *argv[])
{
    auto app = Gtk::Application::create(argc, argv, "org.gtkmm.moving.grid");
  
    MainWindow window;
  
    return app->run(window);
}

假设您将其添加到名为 的文件main.cpp中,您可以使用以下命令构建它:

g++ main.cpp -o example.out `pkg-config --cflags --libs gtkmm-3.0`

推荐阅读