Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - QGridLayout access element at coordinates

Tags:

c++

qt

I have a QGridLayout with a constant number of rows and columns that is filled with instances of QToolButton. What I want to do is to access an object within this layout whose location is determined by its coordinates. I know that there is QGridLayout::->itemAtPosition(row, column) that returns a pointer to QLayoutItem but once I cast it to a QToolButton (which it is, obviously) and try to change something within it I get an access violation exception.

This is how I've tried to cast QLayoutItem* to QToolButton*:

QToolButton* button = dynamic_cast<QToolButton*>(_ui.gridLayoutLeft->itemAtPosition(x, y)); // gridLayoutLeft is of type QGridLayout*

static_cast gave me an "Invalid type conversion" error. What can be done to achieve this behavior?

I'm using VS 2013 with the latest Qt available.

like image 666
Venom Avatar asked Jan 10 '23 22:01

Venom


1 Answers

Try this:

QLayoutItem* item = _ui.gridLayoutLeft->itemAtPosition(x, y);
QWidget* widget = item->widget();
QToolButton* button = dynamic_cast<QToolButton*>(widget); 

In real code don't forget to check for valid pointers.

like image 165
Silicomancer Avatar answered Jan 21 '23 01:01

Silicomancer