首页 > 解决方案 > 将 Gtk::ListStore 添加到 Gtk::TreeView 并将行添加到 ListStore (gtkmm)

问题描述

我希望能够将 Gtk::ListStore 添加到 Gtk::TreeView,treeview 是通过 glade 实现的,但我已经在 C++ 中创建了 ListStore 并向其中添加了列和行。

当我运行代码时,它会显示窗口和从 glade 文件加载的 tree_view,但它是空的。

主窗口.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;
        };
};

主窗口.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);
}

主.cpp:

#include "mainWindow.h"


int main() {
    MainWindow m;
    m.init();
}

标签: c++gtkmm

解决方案


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


推荐阅读