Auto scroll a gtkscrolledwindow - gtk

I have a form interface with a large number of horizontal drop down and text boxes that are inside a GTKscrolledWindow. The form has to be aligned horizontally because there are an unlimited number of forms in the window (think tabel of forms).
Is it (possible/how do I) auto-scroll the GTKScrolledWindow to the right when the operator tabs to the next form control which is off to the right of the screen.?
Related question would be how do I detect if the focused element (button etc) is visible in it's parent scrolledwindow.
Thanks.

I hope you don't mind I am using GTK+ C API in the description, the sollution could be converted to the PyGTK easily and the principles remains the same.
Starting with the second question - if you know which widget to test, you can detect its visibility by calling gtk_widget_translate_coordinates(child, parent, 0, 0, &x, &y) to get the position of the child relative to the parent. By gtk_widget_get_allocation() you get the size of parent and child and you simply test if whole child rectangle is in the scrolled window.
gboolean is_visible_in (GtkWidget *child, GtkWidget *scrolled)
{
gint x, y;
GtkAllocation child_alloc, scroll_alloc;
gtk_widget_translate_coordinates (child, scrolled, 0, 0, &x, &y);
gtk_widget_get_allocation(child, &child_alloc);
gtk_widget_get_allocation(scrolled, &scroll_alloc);
return (x >= 0 && y >= 0)
&& x + child_alloc.width <= scroll_alloc.width
&& y + child_alloc.height <= scroll_alloc.height;
}
You can obtain the curently focused widget in window by gtk_window_get_focus () or you can detect it when focus is changed.
In the autoscroll problem you can handle "focus" signal connected to the widget which can be focussed or the "set-focus-child" event connected to the container containing the widgets. In the signal handler you should check, if the focused widget is visible. If not, determinate its position and scroll properly.
To do so you have to detect the position of the widget inside the whole scrolled area. If you are using some container which does not support scrolling (such GtkHBox) iside GtkScrolledWindow (adapted by viewport), you can get the coordinates of the focused widget relative to the container by gtk_widget_translate_coordinates() again - now using the container instead of scrolled window. The value of the adjustment, if using GtkViewport, the adjustment value correspond to the position in pixels in the scrolled area, so setting adjustment value to x relative coordinate will do scrolling. So the important part of the handler could be
GtkWidget *scrolled = /* The scrolled window */
GtkWidget *container = /* The container in the scrolled window */
GtkWidget *focused = /* The focused widget */
GtkAdjustment *hadj = gtk_scrolled_window_get_hadjustment(
GTK_SCROLLED_WINDOW(scrolled));
gint x, y;
gtk_widget_translate_coordinates (focused, container, 0, 0, &x, &y);
gtk_adjustment_set_value(hadj, min(x, maximal adjustment value allowed);
The maximal adjustment value allowed is adjustment.upper - adjustment.page_size. The focused widget is passed as signal handler argument for both signals, in the case of "set-focus-child" signal you get also the container as argument.

Here's what I did, based on Michy's answer.
To make a scrolled window auto-scroll, run in the constructor:
FocusScroll(scrolledwindow).
class FocusScroll(object):
"""
Get a gtk.ScrolledWindow which contains a gtk.Viewport.
Attach event handlers which will scroll it to show the focused widget.
"""
def __init__(self, scrolledwindow):
self.scrolledwindow = scrolledwindow
self.viewport = scrolledwindow.get_child()
assert isinstance(self.viewport, gtk.Viewport)
self.main_widget = self.viewport.get_child()
self.vadj = scrolledwindow.get_vadjustment()
self.window = self.get_window(scrolledwindow)
self.viewport.connect('set-focus-child', self.on_viewport_set_focus_child)
def get_window(self, widget):
if isinstance(widget, gtk.Window):
return widget
else:
return self.get_window(widget.get_parent())
def is_child(self, widget, container):
"""
Go recursively over all children of container, to check if widget is
a child of it.
"""
for child in container.get_children():
if child is widget:
return True
elif isinstance(child, gtk.Container):
if self.is_child(widget, child):
return True
else:
return False
def on_viewport_set_focus_child(self, _viewport, _child):
idle_add(self.scroll_slide_viewport)
def scroll_slide_viewport(self):
"""Scroll the viewport if needed to see the current focused widget"""
widget = self.window.get_focus()
if not self.is_child(widget, self.main_widget):
return
_wleft, wtop = widget.translate_coordinates(self.main_widget, 0, 0)
wbottom = wtop + widget.get_allocation().height
top = self.vadj.value
bottom = top + self.vadj.page_size
if wtop < top:
self.vadj.value = wtop
elif wbottom > bottom:
self.vadj.value = wbottom - self.vadj.page_size

First, the first.
How do you detect the focus ? You connect to GtkWidget::focus signal.
And in that callback you can scroll the window to whereever you like, how to do that, you need to get the GtkAdjustment of GtkScrolledWindow and move it accordinly to show what you want.

Related

Unity: add different scroll speeds in UI Scroll Rect

In Unity, I created a UI Scroll Rect Object. This object has two children, a Button Handler with different Buttons, and a Background.
Using it, both the Buttons and the Background are scrolling at the same speed. I want the Buttons to scroll faster than the Background, thus creating an effect of depth to the scrolling.
I can not find any options in the Objects or the Scroll Rect for this. Any ideas?
This will require a tiny bit of scripting. The best way in my opinion would involve following steps:
a) for each button, add a component that remembers its start position.
b) grab a scrollrect instance in parent
c) using it to grab an instance of ScrollBar
d) scrollbars have onValueChanged(float) callbacks, you can bind to, to know when the scroll position changes (to avoid doing checks in Update)
e) every time a scrollbar has moved (This will work regardless of whether the user used the scrollbar, or used another mean of scrolling, as the scrollrect will move the scrollbar, which will fire the event anyways), you get a callback with current scrollbar position which will be equal to normalized scrollrect position (0.1)
f) use that value to offset your localposition (something value*parallaxVector2), this should give you a nice cheap depth effect
Here's an example implementation
public class ScrolleRectDepthButton : MonoBehaviour
{
RectTransform content; // we'll grab it for size reference
RectTransform myRect;
public float parallaxAmount = 0.05f;
public Vector2 startPosition;
void Start()
{
myRect = GetComponent<RectTransform>();
startPosition = myRect.anchoredPosition;
ScrollRect scrollRect = GetComponentInParent<ScrollRect>();
content = scrollRect.content;
Scrollbar scrollbar = scrollRect.verticalScrollbar;
scrollbar.onValueChanged.AddListener(OnScrollbarMoved);
}
void OnScrollbarMoved(float f)
{
myRect.anchoredPosition = startPosition - (1 - f) * parallaxAmount * content.rect.height * Vector2.up;
}
}

Hw to Freeze the Button in Scroll bar

I am using unity 2018.3.7. In my project I have instantiate 25 buttons in the scroll bar..I am scrolling the button. It is working well.
Actually i want freeze the 12 the button.When i scroll the button. The 12 th button should be constantly should be there and other button should scroll go up.
scrolling should be done but the freeze button should be constantly there.
Like Excel. If we freeze the top row. The top row is constantly there and scrolling is happened.
Like that i have to do in unity.
How to Freeze the button in scroll bar.
Edit:
Actually I have uploaded new gif file. In that gif file 2 row is freezed (Row Heading1,Row Heading2, Row Heading3,RowHeading4).
2nd row is constantly there. Rest of the the rows 4 to 100 rows are going up.
Like that i have to do ...
How can i do it..
Though your question still is very broad I guess I got now what you want. This will probably not be exactly the solution you want since your question is quite vague but it should give you a good idea and starting point for implementing it in the way you need it.
I can just assume Unity UI here is the setup I would use. Since it is quite complex I hope this image will help to understand
so what do we have here:
Canvas
has the RowController script attached. Here reference the row prefab and adjust how many rows shall be added
Panel is the only child of Canvas. I just used it as a wrapper for having a custom padding etc - it's optional
FixedRowPanel
Here we will add the fixed rows on runtime
Initially has a height of 0!
Uses anchore pivot Y = 1! This is later important for changing the height on runtime
Uses a Vertical Layout Group for automatically arranging added children
ScrollView - Your scrollview as you had it but
Uses streched layout to fill the entire Panel (except later the reduced space for the fixed rows)
Uses anchor pivot Y = 1! Again important for changing the height and position on runtime later
Viewport afaik it should already use streched anchors by default but not sure so make it
Content
Uses a Vertical Layout Group
Initially has a height of 0 (but I set this in the code anyway) and will grow and shrink accordingly when adding and removing rows
And finally RowPrefab
I didn't add its hierachy in detail but it should be clear. It has a Toggle and a Text as childs ;)
Has the Row script attached we use for storing and getting some infos
Now to the scripts - I tried to comment everything
The Row.cs is quite simple
public class Row : MonoBehaviour
{
// Reference these via the Inspector
public Toggle FixToggle;
public Text FixTogText;
public Text RowText;
public RectTransform RectTransform;
// Will be set by RowController when instantiating
public int RowIndex;
private void Awake()
{
if (!RectTransform) RectTransform = GetComponent<RectTransform>();
if (!FixToggle) FixToggle = GetComponentInChildren<Toggle>(true);
if (!FixTogText) FixTogText = FixToggle.GetComponentInChildren<Text>(true);
}
}
And here is the RowController.cs
public class RowController : MonoBehaviour
{
public Row RowPrefab;
public RectTransform ScrollView;
public RectTransform Content;
public RectTransform FixedRowParent;
public int HowManyRows = 24;
public List<Row> CurrentlyFixedRows = new List<Row>();
public List<Row> CurrentlyScrolledRows = new List<Row>();
// Start is called before the first frame update
private void Start()
{
// initially the content has height 0 since it has no children yet
Content.sizeDelta = new Vector2(Content.sizeDelta.x, 0);
for (var i = 0; i < HowManyRows; i++)
{
// Create new row instances and set their values
var row = Instantiate(RowPrefab, Content);
// store the according row index so we can later sort them on it
row.RowIndex = i;
row.RowText.text = $"Row Number {i + 1}";
// add a callback for the Toggle
row.FixToggle.onValueChanged.AddListener(s => HandleToggleChanged(row, s));
// increase the content's size to fit the children
// if you are using any offset/padding between them
// you will have to add it here as well
Content.sizeDelta += Vector2.up * row.RectTransform.rect.height;
// don't forget to add them to this list so we can easily access them
CurrentlyScrolledRows.Add(row);
}
}
// called every time a row is fixed or unfixed via the Toggle
private void HandleToggleChanged(Row row, bool newState)
{
if (newState)
{
// SET FIXED
// Update the button text
row.FixTogText.text = "Unfix";
// Move this row to the fixedRow panel
row.transform.SetParent(FixedRowParent);
// be default we assume we want the first position
var targetIndex = 0;
// if there are other fixed rows already find the first child of FixedRowParent that has a bigger value
if (CurrentlyFixedRows.Count > 0) targetIndex = CurrentlyFixedRows.FindIndex(r => r.RowIndex > row.RowIndex);
// handle case when no elements are found -> -1
// this means this row is the biggest and should be the last item
if (targetIndex < 0) targetIndex = CurrentlyFixedRows.Count;
// and finally in the hierachy move it to that position
row.transform.SetSiblingIndex(targetIndex);
// insert it to the fixed list and remove it from the scrolled list
CurrentlyFixedRows.Insert(targetIndex, row);
CurrentlyScrolledRows.Remove(row);
// Make the fixed Panel bigger about the height of one row
FixedRowParent.sizeDelta += Vector2.up * row.RectTransform.rect.height;
// Make both the scrollView and Content smaller about one row
Content.sizeDelta -= Vector2.up * row.RectTransform.rect.height;
ScrollView.sizeDelta -= Vector2.up * row.RectTransform.rect.height;
// Move the scrollView down about one row in order to make space for the fixed panel
ScrollView.anchoredPosition -= Vector2.up * row.RectTransform.rect.height;
}
else
{
// SET UNFIXED - Basically the same but the other way round
// Update the button text
row.FixTogText.text = "Set Fixed";
// Move this row back to the scrolled Content
row.transform.SetParent(Content);
// be default we assume we want the first position
var targetIndex = 0;
// if there are other scrolled rows already find the first child of Content that has a bigger value
if (CurrentlyScrolledRows.Count > 0) targetIndex = CurrentlyScrolledRows.FindIndex(r => r.RowIndex > row.RowIndex);
// handle case when no elements are found -> -1
// this means this row is the biggest and should be the last item
if (targetIndex < 0) targetIndex = CurrentlyScrolledRows.Count;
// and finally in the hierachy move it to that position
row.transform.SetSiblingIndex(targetIndex);
// insert it to the scrolled list
CurrentlyScrolledRows.Insert(targetIndex, row);
// and remove it from the fixed List
CurrentlyFixedRows.Remove(row);
// shrink the fixed Panel about ne row height
FixedRowParent.sizeDelta -= Vector2.up * row.RectTransform.rect.height;
// Increase both Content and Scrollview height by one row
Content.sizeDelta += Vector2.up * row.RectTransform.rect.height;
ScrollView.sizeDelta += Vector2.up * row.RectTransform.rect.height;
// Move scrollView up about one row height to fill the empty space
ScrollView.anchoredPosition += Vector2.up * row.RectTransform.rect.height;
}
}
}
Result:
As you can see I can now fix and unfix rows dynamically while keeping their correct order within both according panels.

Gtk - draw event fired for wrong widget, and widget not redrawn

I'm trying to create a custom scrollable text area. I created a DrawingArea and a ScrollBar inside a Grid. I have attached the draw event of DrawingArea to this.on_draw method which simply looks at ScrollBar's value and moves the Cairo.Context appropriately before drawing the Pango.Layout.
The first problem is that this.on_draw is getting invoked whenever the ScrollBar is touched even though I have not registered any events with ScrollBar. How do I prevent this, or check this?
The second problem is that even though this.on_draw is invoked, the changes made to the Context is not displayed unless the ScrollBar value is near 0 or 100 (100 is the upper value of Adjustment). Why is this happening?
I did find out that if I connect the value_changed event of ScrollBar to a method that calls queue_redraw of DrawingArea, it would invoke this.on_draw and display it properly after it. But due to the second problem, I think this.on_draw is getting invoked too many times unnecessarily. So, what is the "proper" way of accomplishing this?
using Cairo;
using Gdk;
using Gtk;
using Pango;
public class Texter : Gtk.Window {
private Gtk.DrawingArea darea;
private Gtk.Scrollbar scroll;
private string text = "Hello\nWorld!";
public Texter () {
GLib.Object (type: Gtk.WindowType.TOPLEVEL);
Gtk.Grid grid = new Gtk.Grid();
this.add (grid);
var drawing_area = new Gtk.DrawingArea ();
drawing_area.set_size_request (200, 200);
drawing_area.expand = true;
drawing_area.draw.connect (this.on_draw);
grid.attach (drawing_area, 0, 0);
var scrollbar = new Gtk.Scrollbar (Gtk.Orientation.VERTICAL,
new Gtk.Adjustment(0, 0, 100, 0, 0, 1));
grid.attach (scrollbar, 1, 0);
this.darea = drawing_area;
this.scroll = scrollbar;
this.destroy.connect (Gtk.main_quit);
}
private bool on_draw (Gtk.Widget sender, Cairo.Context ctx) {
ctx.set_source_rgb (0.9, 0.9, 0.9);
ctx.paint ();
var y_offset = this.scroll.get_value();
stdout.printf("%f\n", y_offset);
ctx.set_source_rgb (0.25, 0.25, 0.25);
ctx.move_to(0, 100 - y_offset);
var layout = Pango.cairo_create_layout(ctx);
layout.set_font_description(Pango.FontDescription.from_string("Sans 12"));
layout.set_auto_dir(false);
layout.set_text(this.text, this.text.length);
Pango.cairo_show_layout(ctx, layout);
return false;
}
static int main (string[] args) {
Gtk.init (ref args);
var window = new Texter ();
window.show_all ();
Gtk.main ();
return 0;
}
}
Also, please point out any (possibly unrelated) mistake if you find one in the above code.
The part that you are missing is that a draw signal does not mean "redraw everything". Instead, GTK+ sets the clip region of the cairo context to the part that needs to be redrawn, so everything else you do doesn't have any effect. The cairo function cairo_clip_extents() will tell you what that region is. The queue_draw_area() method on GtkWidget will allow you to explicitly mark a certain area for drawing, instead of the entire widget.
But your approach to scrollbars is wrong anyway: you're trying to build the entire infrastructure from scratch! Consider using a GtkScrolledWindow instead. This automatically takes care of all the details of scrolling for you, and will give you the overlay scrollbars I mentioned. All you need to do is set the size of the GtkDrawingArea to the size you want it to be, and GtkScrolledWindow will do the rest. The best way to do this is to subclass GtkDrawingArea and override the get_preferred_height() and/or get_preferred_width() virtual functions (being sure to set both minimum and natural sizes to the sizes you want for that particular dimension). If you ever need to change this size later, call the queue_resize() method of GtkWidget. (You probably could get away with just using set_size_request(), but what I described is the preferred way of doing this.) Doing this also gives you the advantage of not having to worry about transforming your cairo coordinates; GtkScrolledWindow does this for you.

How to Drag and Drop Custom Widgets?

I have created my own custom widget and I want to support internal drag and drop for the widgets.
I have added 4 of my custom widgets in a vertical box layout. Now i want to drag and drop the custom widgets internally. To be more clear, If i drag the last widget and drop it in the first position, then the first widget has to move to the second positon and the last widget (which is dragged) has to move to first position. (same like drag and drop of the items in the List view). Can anyone suggest me a way to drag and drop of the custom widgets.
You need to reimplement mousePressEvent, mouseMoveEvent and mouseReleaseEvent methods of a widget you want to drag or install an event filter on them.
Store the cursor position in mousePressEvent and move the widget in mousePressEvent to the distance the cursor moved from the press point. Don't forget to clear the cursor position in the mouseReleaseEvent. The exact code depends of how you want the widget to look when is being dragged and how other widgets should behave when drag/drop the widget. In the simplest case it will look like this:
void mousePressEvent(QMouseEvent* event)
{
m_nMouseClick_X_Coordinate = event->globalX();
m_nMouseClick_Y_Coordinate = event->globalY();
};
void mouseMoveEvent(QMouseEvent* event)
{
if (m_nMouseClick_X_Coordinate < 0)
return;
const int distanceX = event->globalX() - m_nMouseClick_X_Coordinate;
const int distanceY = event->globalY() - m_nMouseClick_Y_Coordinate;
move(x() + distanceX, y() + distanceY());
};
void mouseReleaseEvent(QMouseEvent* event)
{
m_nMouseClick_X_Coordinate = -1;
}

Gtk How to add GtkMenu widget at end edge of widget

I have a GtkMenu Widget and i am adding it to screen on button click,,
but it gets added at mouse location but i want to add it to end edge of button widget like,
+-------+
|BUTTON |
+-------+
+------------+
|Menu Item 1 |
|Menu Item 2 |
+------------+
I am using following code to add popup menu
// Add popup menu.
gtk_menu_popup( GTK_MENU (widget), NULL, NULL, NULL, NULL,
bevent->button, bevent->time);
Ok added this function but popup menu gets added to end of window not at the end of button widget...
void set_position (GtkMenu *menu, gint *px, gint *py, gboolean *push_in, gpointer data)
{
gint w, h;
GtkBuilder *builder = GetBuilderPointer();
GtkWidget *button = GTK_WIDGET( gtk_builder_get_object( builder, "button_presence"));
gdk_window_get_size (button->window, &w, &h);
gdk_window_get_origin (button->window, px, py);
*py = h;
printf("\n\n w[%d] h[%d] px[%d] py[%d]\n\n", w, h, *px, *py );
*push_in = TRUE;
}
Printf gives output like follows,
w[350] h[400] px[341] py[607]
i am not able to retrieve x, y, height, width of button widget...
Note: This button is a custom widget with (GtkHBox+(GtkImage+GtkLabel)) in it.
thanks unwind for your answer.
The fourth argument to gtk_menu_popup() is a pointer to a GtkMenuPositionFunc, which is a callback that you can define. You need to add such a callback, and have it return the desired position, by reading it out of the button widget's GdkWindow.
It's been a while since I did this, but you might also have to read out the parent window's position on-screen, and add the widget's position to them to get the absolute coordinates where you want the menu to pop up.