Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current row of QTableWidget if I clicked on its child?

I have created a QTableWidget in which I've used setCellWidget(QWidget*). I've set QLineEdit in the cell widget. I've also created a delete button and clicking that button sends a signal to the function deleteRow. I've also used a function currentRow() to get the current row, but it returns -1 because of the QLineEdit. The code snippet is below.

void createTable() {
    m_table = new QTableWidget(QDialog); //member variable
    for (int i = 0; i < 3; i++)
    {
        QLineEdit *lineEdit = new QLineEdit(m_table);
        m_table->setCellWidget(i, 0, lineEdit);
    }
    QPushButton *deleteBut = new QPushButton(QDiaolg);
    connect(deleteBut, SIGNAL(clicked()), QDialog, SLOT(editRow()));
}

editRow() {
    int row = m_table->currentRow(); // This gives -1
    m_table->remove(row);
}

In above scenario I click in the QLineEdit and then click on the button delete. Please help me out with a solution.

like image 356
njporwal Avatar asked Jan 26 '26 08:01

njporwal


1 Answers

Just tried it here, it seems that currentRow of the table returns -1 when clicking the button right after program start, and when first selecting a cell, then selecting the QLineEdit and then clicking the button, the correct row is returned.

I would do the following as a workaround: Save the row number in the QLineEdit, e.g. by using QObject::setProperty:

 QLineEdit *lineEdit = new QLineEdit(m_table);
 lineEdit->setProperty("row", i);
 m_table->setCellWidget(i, 0, lineEdit);

Then, in the editRow handler, retrieve the property by asking the QTableWidget for its focused child:

int row = m_table->currentRow();
if (row == -1) {
  if (QWidget* focused = m_table->focusWidget()) {
    row = focused->property("row").toInt();
  }
}
like image 134
Karsten Koop Avatar answered Jan 27 '26 23:01

Karsten Koop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!