Is there a way to determine the precise cursor position within a cell of a Gtk IconView when it is clicked?

Looking to determine if a specific position in a Gtk Iconview cell was clicked on (highlighted by the blue box in the image).

In my exploration, I discovered two methods for obtaining cursor position:

Method 1: Use POINTER_MOTION_MASK to detect cursor location within the IconView

i.e.

 self.iconview.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
 self.iconview.connect("motion-notify-event", self.on_pointer_motion)

This allows you to find the current cursor position and cell:

 def on_pointer_motion(self, widget, event):
    path= self.get_path_at_pos(event.x, event.y)

Method 2: Connect to "button-press-event"

 self.iconview.connect("button-press-event", self.on_mouse_click)

 def on_mouse_click(self, widget, event):
    path= self.get_path_at_pos(event.x, event.y)

The challenge is tying event.x and event.y to a specific area within the cell indicated by the blue box.

After reviewing resources for GtkCellArea, GtkCellAreaBox, and GtkIconView, no direct event/function seems available for this purpose.

Seeking guidance on how to approach solving this issue.

Currently utilizing Python 2.7 & GTK+ 3.2 for development, with plans to support python 3+ and all versions of GTK beyond GTK+ 3.2 as well.

Answer №1

It's not as difficult as it seems.

Here is a snippet of code from my PyGObject project named Playlist.py. In this code, I connect the signal button-press-event of GtkIconView to check the event type and obtain the path using the method iconview.get_path_at_pos(...). The path can be either None or the position of the selected cell based on the cursor position. For more details about the project, you can visit the GitHub repository at https://github.com/LiuLang/babystory

# Copyright (C) 2013 LiuLang <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbacb8beb8a3b1a3b8a4b8acb8be8baca6aaa2a7e5a8a4a6">[email protected]</a>>

# This source code is distributed under the GPLv3 license which can be found
# at http://www.gnu.org/licenses/gpl-3.0.html

from gi.repository import GdkPixbuf
from gi.repository import Gdk
from gi.repository import Gtk
import json
import random

from babystory.Cache import Cache
from babystory import Config
from babystory import Net
from babystory import Utils
from babystory import Widgets

_ = Config._
TITLE, SIZE, DURATION, URL, CATEGORY = list(range(5))


def song_row_to_dict(song_row):
    song = {
            'Title': song_row[TITLE],
            'Size': song_row[SIZE],
            'Duration': song_row[DURATION],
            'Url': song_row[URL],
            'Category': song_row[CATEGORY],
            }
    return song

class Playlist(Gtk.Box):
    def __init__(self, app):
        self.app = app
        super().__init__()

        # Rest of the Python script for Playlist class...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting data from an HTML table on a website

I need assistance in generating a Python dictionary mapping color names to background colors from this color palette. What is the most effective method to extract the color name strings and corresponding background color hex values? The objective is to cr ...

What steps should I follow to create the decrypt function for the encrypt function I've implemented?

Recently, I've come across an encrypt function that I am struggling with: def encrypt(password): for i in (password): not_Encrpyted = ''.join(dict_Chiper[i] for i in password) Encrpyted = ''.join(reversed(n ...

Encountering a NoSuchElementException while attempting to utilize Selenium with Python

I am encountering a NoSuchElementException when attempting to locate an element using Selenium in Python. I have ensured that the page fully loads and that I am switching to the correct frame. Below is the code snippet: driver.get("https://www.arcgis.com ...

What is the best way to optimize the function using Keras Tuner?

Is there a way to fine-tune the optimization function using Keras Tuner? I'm interested in experimenting with SGD, Adam, and RMSprop. I've attempted: hp_lr = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4]) hp_optimizer = hp.Choic ...

Get the value of a CSS property in Python by parsing the rendered HTML

Currently, I am using Selenium and PhantomJS in conjunction with Python for the purpose of crawling rendered web pages. While it is a straightforward process to identify the presence of specific words within the HTML content (e.g. if "example" in html...), ...

Discovering the process of choosing a city name during web scraping in Python for Justdial

As a newcomer to web scraping, I am attempting to extract information from the Just Dial website. My goal is to allow users to enter any city name of their choice directly into the program. When using the code snippet below: driver.find_element(By.XPATH,&q ...

Identifying file formats with Python

Being a beginner in Python, I have some doubts regarding data types. For instance, if I write the code wordfile = open("Sentence.txt","w"), what would be the data type of "wordfile"? ...

establish pricing for purchases using or-tools

Efficiency is key when it comes to minimizing costs associated with fuel consumption for our vehicles. Sometimes, customers may require an extra staff member during their product purchases, which incurs a fixed daily cost. Our goal is to reduce this additi ...

Tips for displaying the href of a table cell that contains a specific word

Looking to extract specific href links from a web application that are labeled as "Show on diagram." Below is an image of the HTML I want to retrieve: web application code This is my Python script: import webbrowser from bs4 import BeautifulSoup import ...

The 'WebDriver' instance does not have the method 'find_element_by_name'

When I execute the code, it briefly opens the Instagram page for a couple of seconds before closing and displaying this error message: 'WebDriver' object has no attribute 'find_element_by_name' Upon running the code again, it repeats ...

I'm curious, where exactly do pip and conda store the record of installed packages to track who installed each one?

After running some pip install commands within my conda environment, I noticed that both conda and pip stick to the Python convention of installing packages into the site-packages directory. Upon checking with pip list and conda list, I found that they ha ...

Navigating the Zeppelin: A Guide to Understanding DataFrames via SQL

I am new to using Python with Zeppelin and I am trying to import a dataframe into Zeppelin through SQL. However, I have only found materials about PySpark in Zeppelin so far. %python import pandas as pd #To work with dataset import numpy as np #Math l ...

Choosing the primary column in a pandas dataframe

import pandas as pd dataframe1 = pd.DataFrame({'customer' : ['customer2', 'customer1'], 'item1': [12, 13], 'item2' : [3, 28],'item3': [2, 1]}) dataframe2 = pd.DataFrame({'customer' : ...

The presence of a function within the __repr__ method causes an endless loop

Currently, I am in the process of learning Python and recently attempted to code something new. class AttributeDisplay: '''A class that showcases all attributes within __repr__. It can be inherited.''' def gatherA ...

Python2 has the site-packages folder, while Python3 does not have it

When I am logged in as the root user, I noticed the following: root@5d6f29f1d4e9:/usr/local/lib/python2.7# ls -a . .. dist-packages site-packages root@5d6f29f1d4e9:/usr/local/lib/python3.6# ls -a . .. dist-packages Upon running this command: find / ...

Tips for extracting user stories from a project using Pyral

I am attempting to retrieve all the UserStories associated with a specific Project (let's say project 'Bolt' in workspace 'ABC'). Once I establish the connections (using username, password, and server) and set my workspace to the ...

Organizing the rows/index in a pivot table

Consider the dataframe shown below: df = pd.DataFrame({'A': ['John', 'Boby', 'Mina', 'Peter', 'Nicky','Teena'], 'B': ['John', 'Boby', 'Mina' ...

What is the method for sorting a Python list both numerically in descending order and alphabetically in ascending order simultaneously?

My goal is to arrange a list that contains tuples with a word and a number. my_list = [('hello',25), ('hell',4), ('bell',4)] I am looking for a way to sort this list (maybe using lambda) in order to achieve the following: [ ...

troubles with ffmpeg subprocess

This code segment functions properly when executed through the Python script editor in Maya. How can I ensure that it will also run successfully when executed as part of a script? oneImage = "D:/imagesequence/dpx/brn_055.0000.jpg" firstImage = "c:/users ...

I find it puzzling that the multi-threaded code is unable to retrieve the lineedit text

Below is the code snippet I use: class QWidgetUI(QWidget): def __init__(self): super().__init__() self.IDinput = QLineEdit(self) self.searchBtn = QPushButton(" ...