下面的例子是用 Gtkmm 3.24 编写的,它创建了一个窗口,其中三个按钮在 Gtk::Grid 内共存。点击 Switch 按钮将在网格内交换 A 和 B。这里的关键思想是
-
Gtk::Grid::remove 要移动的小部件。
-
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`