c++ - 将 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();
}
解决方案
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
推荐阅读
- flask - Python烧瓶资源
- discord.js - 根据游戏活动移动人们的 Discord 机器人
- arrays - 包含指针的结构上的指针:数组命名法有效,但不是 (ptr + 1)。为什么?
- python - self 对象不可下标
- c# - Xamarin.Forms 和 Prism - 如何传递数据并导航到另一个视图?
- image - JavaFX Image 和 ImageViewer 不支持 jpeg
- flutter - Dart Native Library - 为 Android 和 iOS 编译
- javascript - 正确访问 Vue 3 中的反应式数组
- laravel - Laravel 按需通知不发送电子邮件
- plotly-python - python-plotly-multiple y-axis:如何关闭两个子图上的网格?