将文本添加到文本缓冲区时GTK TextView自动滚动
我正在尝试创建一个非常简单的类似日志的GUI应用程序,它只动态和异步地显示日志文件中的文本。问题是,当日志文件更新时,GUI中的文本视图会回滚到第1行。每次尝试修复都失败了,我想知道我是否在GTK中偶然发现了一个bug。以下是我的代码摘要:将文本添加到文本缓冲区时GTK TextView自动滚动,gtk,gtk3,vala,Gtk,Gtk3,Vala,我正在尝试创建一个非常简单的类似日志的GUI应用程序,它只动态和异步地显示日志文件中的文本。问题是,当日志文件更新时,GUI中的文本视图会回滚到第1行。每次尝试修复都失败了,我想知道我是否在GTK中偶然发现了一个bug。以下是我的代码摘要: using Cairo; using Gtk; namespace ServerManager { public class ServerManager : Window { public TextView text_view;
using Cairo;
using Gtk;
namespace ServerManager {
public class ServerManager : Window {
public TextView text_view;
public TextIter myIter;
public TextMark myMark;
public async void read_something_async (File file) {
var text = new StringBuilder ();
var dis = new DataInputStream (file.read ());
string line;
while ((line = yield dis.read_line_async (Priority.DEFAULT)) != null) {
text.append (line);
text.append_c('\n');
}
this.text_view.buffer.text = text.str;
text_view.buffer.get_end_iter(out myIter);
text_view.scroll_to_iter(myIter, 0, false, 0, 0);
}
public static int main (string[] args) {
Gtk.init (ref args);
var window = new ServerManager ();
// The read-only TextView
window.text_view = new TextView ();
window.text_view.editable = false;
window.text_view.cursor_visible = false;
window.text_view.wrap_mode = Gtk.WrapMode.WORD;
// Add scrolling functionality to the TextView
var scroll = new ScrolledWindow (null, null);
scroll.set_policy (PolicyType.AUTOMATIC, PolicyType.AUTOMATIC);
scroll.add (window.text_view);
// Vbox so that our TextView has someplace to live
var vbox = new Box (Orientation.VERTICAL, 0);
vbox.pack_start (scroll, true, true, 0);
window.add (vbox);
window.set_border_width (12);
window.set_position (Gtk.WindowPosition.CENTER);
window.set_default_size (800, 600);
window.destroy.connect (Gtk.main_quit);
window.show_all ();
File file = File.new_for_path ("/home/user/temp.log");
FileMonitor monitor = file.monitor (FileMonitorFlags.NONE, null);
stdout.printf ("Monitoring: %s\n", file.get_path ());
monitor.changed.connect (() => {
window.read_something_async(file);
});
Gtk.main ();
return 0;
}
}
}
我还尝试使用TextMarks而不是ITER,但没有任何影响。之所以会滚动到第一行,是因为read\u something\u async()删除缓冲区的当前内容,然后写入新内容(这是设置text属性的作用)。也许这就是你想要的,但除非你一直跟踪滚动的位置,否则你会丢失它 您的卷轴\u to \u iter()未按预期工作的原因可能是: 请注意,此函数使用文本缓冲区中当前计算的行高度。在空闲处理程序中计算线高度;因此,如果在高度计算之前调用此函数,可能不会产生预期效果。为了避免奇怪,请考虑使用GTKXTrimeVIEWScLoopToMax()来保存一个点,以便在行验证之后滚动。 使用“右重力”文本标记调用TextView.ScrollToMark()应该对您有用