How to Get the Position of a Widget in a Cell (QTableWidget)

In this article I describe how you can get the position (row and column) of a Widget in a Cell, or to be precise, how to get row and column of a QWidget in a QTableWidget. This is specially useful in case you have a button or any other widget and you want to perform a task specific to that widget when it is pressed or triggered in any way.

First of all, if you do not already have the widget in a variable then try to do that first. Here I assume that you are using signals and slots, if that is the case you can get the widget using sender() function and type-casting. Let’s say you have a widget named details_btn and a table named some_table:

QWidget *details_btn = (QWidget*)sender();

Then you can just simply compare the cellWidget items with your widget and see if any one of them matches yours:

for (int i = 0; i < ui->some_table->rowCount(); i++)
{
	for (int j = 0; j < ui->some_table->columnCount(); j++)
	{
		if (ui->some_table->cellWidget(i, j) == details_btn)
			ui->some_table->setCurrentCell(i, 0);
	}
}


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.