gtk textview控件防止自动扩展大小

⌚Time: 2025-01-19 20:27:00

👨‍💻Author: Jack Ge

如果gtktextview控件显示的文本过长,会自动横向扩展软件界面,为了防止这种情况,通过gtk_text_view_set_wrap_mode可以设置文本控件自动换行,横向就不会自动扩展。


gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(g_scanTextView), GTK_WRAP_CHAR);

其中的第二个参数GtkWrapMode是一个枚举类型,详情可以查阅gtk文档。

typedef enum
{
  GTK_WRAP_NONE,
  GTK_WRAP_CHAR,
  GTK_WRAP_WORD,
  GTK_WRAP_WORD_CHAR
} GtkWrapMode;

至于纵向的自动扩展,可以通过加滚动窗口实现,把textview控件加入到一个scrolledwindow窗口里

//滚动窗口
GtkWidget *scrolledWindow = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledWindow),
                                   GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
// 将文本视图添加到滚动窗口中
gtk_container_add(GTK_CONTAINER(scrolledWindow), g_scanTextView);

gtk_scrolled_window_set_policy可以设置水平和垂直的滚动策略,其中的GTK_POLICY_NEVER、GTK_POLICY_AUTOMATIC是一些滚动策略。分别代表从不滚动、自动滚动,还有一个GTK_POLICY_ALWAYS表示总是滚动

这样在垂直方向超出空间会自动出现滚动条而不是扩展软件大小。


关于gtkscrolledwindow,gtk2文档有下面的解释。

The scrolled window can work in two ways. Some widgets have native scrolling support; these widgets have "slots" for GtkAdjustment objects. [5] Widgets with native scroll support include GtkTreeView, GtkTextView, and GtkLayout.

For widgets that lack native scrolling support, the GtkViewport widget acts as an adaptor class, implementing scrollability for child widgets that lack their own scrolling capabilities. Use GtkViewport to scroll child widgets such as GtkTable, GtkBox, and so on.

If a widget has native scrolling abilities, it can be added to the GtkScrolledWindow with gtk_container_add(). If a widget does not, you must first add the widget to a GtkViewport, then add the GtkViewport to the scrolled window. The convenience function gtk_scrolled_window_add_with_viewport() does exactly this, so you can ignore the presence of the viewport.

对于原生支持滚动的控件可以直接使用gtk_container_add向tkscrolledwindow添加控件,不支持原生滚动的控件比如GtkTable,需要使用gtk_scrolled_window_add_with_viewport添加到gtkscrolledwindow。