Selecting row on GtkColumnView at right mouse click position

I want to select current item in GtkColumnView when users presses right mouse button.

After installing controller

GtkGesture* rightClick = gtk_gesture_click_new();
    gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(rightClick), GDK_BUTTON_SECONDARY);
    gtk_widget_add_controller (wdgSWTable, GTK_EVENT_CONTROLLER(rightClick));
    g_signal_connect (rightClick, "pressed", G_CALLBACK (secondaryButtonPressedOnGtkcolumnView), wdgSWTable);

I implemented the following handler:

static void secondaryButtonPressedOnGtkcolumnView(GtkGestureClick* self, gint n_press, gdouble x, gdouble y, gpointer user_data)
{
    GtkScrolledWindow* scrolledWindow = GTK_SCROLLED_WINDOW(user_data);
    GtkWidget* colView = gtk_scrolled_window_get_child(scrolledWindow);
    
    GtkAdjustment* vAdjustment = gtk_scrolled_window_get_vadjustment (scrolledWindow);
    double yOffset = gtk_adjustment_get_value (vAdjustment);
    
    GtkColumnView* columnView = GTK_COLUMN_VIEW(colView);
    size_t nRows = getNumberOfRows(columnView);
    GtkSingleSelection* selection = (GtkSingleSelection *)gtk_column_view_get_model(columnView);
    GListModel* model = gtk_single_selection_get_model(selection);
    
    double scrollHeight = gtk_adjustment_get_upper(vAdjustment);
    
    int pageSize = gtk_adjustment_get_page_size(vAdjustment);
    
    int clientHeight = gtk_widget_get_allocated_height(colView);
    if (scrollHeight < 1)
        return;
    
    double rowHeight = scrollHeight / (double)nRows;
    if (rowHeight <= 0)
        return;
    if (pageSize < scrollHeight-0.1)
    {
        // y is the click position relative to GtkColumnView
        int clickedRow = (int)((y + yOffset) / rowHeight) - 1;
        
        if (clickedRow >= 0 && clickedRow < nRows)
        {
            gtk_single_selection_set_selected(selection, clickedRow);
        }
    }
}

However, this method works only if number of elements in GtkColumnView exceeds page size of scrolled window. If number of elements is small, then it doesn’t work. Any idea how to implement this without calculating rowHeight in GtkColumnView. The column view works in single selection mode and I am using gtk 4.18.5.

1 Like

Shortly, I just need to select the underlaying row when the user clicks the right mouse button on GtkColumnView. There must be a simple solution for this.

Maybe it would be easier to add the right-click handling not in the columnview, but rather in the row widgets when they are bound? This way, you’d know when the callback fires on which item you are, and you wouldn’t have any issue with places where the are no items: no item, no callback.

Hope my explanation is clear.