我希望能够将Gtk :: ListStore添加到Gtk :: TreeView,树视图是通过林间空地实现的,但是我已经用C ++创建了ListStore,并向其中添加了列和行。
当我运行代码时,它显示窗口和从glade文件中加载的tree_view,但它为空。
mainWindow.h:
#pragma once
#include <gtkmm.h>
class MainWindow {
protected:
Gtk::Window *main_window;
Gtk::TreeView *tree_view;
Glib::RefPtr<Gtk::ListStore> list_store;
public:
void init();
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns() { add(name); add(age); }
Gtk::TreeModelColumn<Glib::ustring> name;
Gtk::TreeModelColumn<Glib::ustring> age;
};
};
mainWindow.cpp:
#include "mainWindow.h"
void MainWindow::init() {
auto app = Gtk::Application::create("org.gtkmm.example");
auto builder = Gtk::Builder::create_from_file("test.glade");
builder->get_widget("main_window", main_window);
builder->get_widget("tree_view", tree_view);
ModelColumns columns;
list_store = Gtk::ListStore::create(columns);
tree_view->set_model(list_store);
Gtk::TreeModel::Row row = *(list_store->append());
row[columns.name] = "John";
row[columns.age] = "30";
row = *(list_store->append());
row[columns.name] = "Lisa";
row[columns.age] = "27";
app->run(*main_window);
}
main.cpp:
#include "mainWindow.h"
int main() {
MainWindow m;
m.init();
}
tree_view->set_model(list_store);
告诉tree_view
将list_store
用作其TreeModel,但没有说明要从list_store
的哪一列进行渲染。实际上,默认行为是不呈现任何列。
要渲染两列,您需要让tree_view
附加它们。
// "Name" is column title, columns.name is data in the list_store
tree_view->append_column("Name", columns.name);
tree_view->append_column("Age", columns.age);
Gtkmm有官方教程。这是关于树视图的部分。 https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview.html.en