将Gtk :: ListStore添加到Gtk :: TreeView并将行添加到ListStore(gtkmm)

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

我希望能够将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();
}
c++ gtkmm
1个回答
0
投票
tree_view->set_model(list_store);

告诉tree_viewlist_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

© www.soinside.com 2019 - 2024. All rights reserved.