1
votes

I have QPushbutton in each row of QTreeWidget. I want to get the index of rows on click event of QPushbutton. I am using this:

QPushButton btn=new QPushButton();
QTreeWidgetItem *Items=new QTreeWidgetItem(ui->treeWidget);
ui->treeWidget->setItemWidget(Items,0,btn);
connect(btn,SIGNAL(clicked()),this,SLOT(OnPreview()))

On this click event i want to get the index of the row of clicked button ? Thanks, Ashish

2
You need either to calculate the index in OnPreview() slot, or keep mapping between button and the index it assigned to.vahancho
thnx vahancho, I know i have to do it in OnPreview(). but how that is main point..? Any guesses..?Ashish

2 Answers

3
votes

If the rows can't be moved I would suggest to use a property:

Example for plain structure, use complex index for tree structure:

QPushButton btn=new QPushButton();
btn->setProperty("row", ui->treeWidget->topLevelItemCount());

void OnPreview()
{
  int row = sender()->property("row").toInt();
  QTreeWidgetItem* item = ui->treeWidget->topLevelItem(row);
}

Otherwise, if rows amount if not too large you can loop by items to find out which of them contains the button:

Example for plain structure, use complex index for tree structure:

void OnPreview()
{
   for(int i = 0 ; i < ui->treeWidget->topLevelItemCount() ; i++)
   {
      QTreeWidgetItem* item = ui->treeWidget->topLevelItem(i);
      if (ui->treeWidget->itemWidget(item, 0) == sender())
      {
          ...
      }
   }
}

If you have great amount of rows and they can be moved, create a hash table to match buttons and items:

QHash<QObject*, QTreeWidgetItem*> hash;

QPushButton* btn=new QPushButton();
QTreeWidgetItem *Items=new QTreeWidgetItem(ui->treeWidget);
hash[btn] = Items;

void OnPreview()
{
   QTreeWidgetItem* item = hash[sender()];
   ...
}
1
votes

First you need to define a map, that will store your push buttons and corresponding indexes. Do this preferably as a member variable of your class:

QMap<QObject, QModelIndex> map;

Than, in the function where you create buttons:

{
     [..]
     QPushButton *btn = new QPushButton();
     QTreeWidgetItem *Items = new QTreeWidgetItem(ui->treeWidget);
     ui->treeWidget->setItemWidget(Items, 0, btn);
     connect(btn, SIGNAL(clicked()), this, SLOT(OnPreview()));

     QModelIndex index = ui->treeWidget->indexFromItem(Items);
     map.insert(btn, index);
     [..]
}

And finally your slot:

void OnPreview()
{
    QObject *btn = sender();
    QModelIndex index = map.value(btn);
    [..]
}