Search code examples
c++qtqt5qtablewidgetqcombobox

how to get row number after comboBox item in QTableWidget in qt


I would like to get a number of a QTableWidget row after selecting some topic in comboBox how it is possible to get the row, enter image description herethanks.

void MainWindow::metto_stringa(int i)
{
    QWidget *w = qobject_cast<QWidget *>(sender()->parent());
    if(w)
    {
        int row = ui->tableWidget->indexAt(w->pos()).row();
        ui->lineEdit->setText(QString::number( row ));
    }
    // ui->lineEdit->setText(QString::number( i ));
}

else if(i == 3)
{
     // ui->tableWidget->setCellWidget(ui->tableWidget->rowCount(), i, "");
      QString s = "Normal";
      QComboBox *combo = new QComboBox;
      combo->addItem("Below normal");
      combo->addItem("Normal");
      combo->addItem("Above normal");
      combo->addItem("High");
      combo->addItem("Real time");
      connect(combo,SIGNAL(currentIndexChanged(int)),this,
      SLOT(metto_stringa(int)));
      ui->tableWidget->setCellWidget(ui->tableWidget->rowCount()-1,  i,combo);
      /*  ui->tableWidget->setCellWidget(i,4,combo);
      QTableWidgetItem*item = new QTableWidgetItem(s);
      item->setFlags(item->flags() ^ Qt::ItemIsEditable);
      ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, i, 
      item);*/
      continue;
}

Solution

  • In this case you should not use the parent of the QComboBox, you must use the same sender()

    void MainWindow::metto_stringa(int index)
    {
        QWidget *w = qobject_cast<QWidget *>(sender());
        if(w)
        {
            int row = ui->tableWidget->indexAt(w->pos()).row();
            ui->lineEdit->setText(QString::number(row));
        }
    }
    

    In the question I answered before I commented that you must access the widget that you use in the setCellWidget() function, in the previous case the widget had the following form:

    QWidget <--- QPushButton
    parent()     sender()
    

    ie you owe to that widget so we take advantage of sender() and parent() in the previous case. In the current case QComboBox is added directly.