我正在尝试使用以下方法将多行数据插入我的 TextView(大约 5-10 行):
Glib::RefPtr<Gtk::TextBuffer> buffer = txtView.get_buffer();
buffer->set_text("");
Gtk::TextBuffer::iterator iter;
iter = buffer->get_iter_at_offset(0);
iter = buffer->insert(iter, myString);
其中“myString”是一个格式良好的字符串(设置了结束行),它是从另一个函数传递过来的。 “myString”的示例如下:
- This is Line One
This is Line Two
Blablabla
This is Line Three
Blablabla
字符串的内容在每次函数调用时都是不同的。我的问题是我试图将不同的缓冲区应用于字符串的不同行。
例如,我想为第 2 行应用蓝色背景色,为第 3 行应用绿色背景色,为第 5 行应用红色背景色。这怎么可能呢,因为我将我的数据行作为整个字符串,而不是逐行传递。 (我无法逐行传递所有这些,因为我的程序是多线程的,这不太好)。
我做过类似的事情,但这只会改变 TextView 的整个缓冲区,而不是特定的行。
buffer->property_background() = "red";
txtView->set_buffer(buffer);
最佳答案
正如andlabs所说,你需要使用Gtk::TextBuffer::Tag。请先找到一些片段。这里的引用是https://developer.gnome.org/gtkmm-tutorial/stable/sec-textview-buffer.html.sl
创建必要的 TagTable 和 Tag,为 Tag 分配属性并将 Tag 添加到 TagTable。
m_reftagtable = Gtk::TextBuffer::TagTable::create();
reftagmatch = Gtk::TextBuffer::Tag::create();
reftagmatch->property_background() = "orange";
m_reftagtable->add(reftagmatch);
使用 TagTable 创建一个 Textbuffer
m_textbuffer = Gtk::TextBuffer::create(m_reftagtable);
m_textview->set_buffer(m_textbuffer);
让我们假设您有一些条件,并且根据 plaintextcondition 的 bool 状态,您可以添加纯文本或带有橙色背景的文本。
iterend = m_textbuffer->get_iter_at_offset(m_textbuffer->get_char_count());
if (plaintextcondition){
m_textbuffer->insert(iterend, "Plain text");
} else {
m_textbuffer->insert_with_tag(iterend, "Orange Text", refTagMatch);
}
当然这只是一个提示。请参阅引用资料以获取更多信息。
关于C++ GTKmm - 将文本插入到具有多个缓冲区和更改文本的 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085407/