QTableWidget dynamically adds controls in the cell to get the column and row where it is located

Recently, when using QTableWidget, I encountered dynamically adding controls in the cell, such as QPushButton, QComboBox, etc. Adding is very simple, directly using the function QTableWidget::setCellWidget(int row, int column, QWidget widget) can be added successfully, but How to get where the ranks become a problem.
I found related methods on the Internet, and most of them use the method of clicking the control to get its row and column; the
slot function corresponding to the button:
QPushButton
pButton = qobject_cast<QPushButton*>(sender());
int x = pButton- >frameGeometry().x();
int y = pButton->frameGeometry().y();
QModelIndex index = ui.tableWidget->indexAt(QPoint(x, y));
int iRow = index.row();
int iCol = index.column();

In this way, the current row and column are obtained, but all I get are 0 rows and 0 columns, and many friends in the comment area also encountered the same problem. After careful analysis, the problem appeared on the add button, because I What needs to be added is two buttons, so a layout and QWidget* btns = new QWidget(this); are added, so that the obtained position is always in the btns of the button, so it is always 0,0.
Renderings:
insert image description here

Look directly at the corrected complete code:
add button code:

QHBoxLayout* hlayout = new QHBoxLayout();
hlayout->addStretch();
QPushButton* modify = new QPushButton(this);
QPushButton* remove = new QPushButton( this);
connect(modify, &QPushButton::clicked, this, &AlgoForm::modifyBtnClicked);
connect(remove, &QPushButton::clicked, this, &AlgoForm::removeBtnClicked);
hlayout->addWidget(modify);
hlayout->addWidget(remove);
hlayout->addStretch();
QWidget* btns = new QWidget(this);
btns->setLayout(hlayout);
ui->tableWidget->setCellWidget(row, 6, btns); //两按键添加到表格的row行,6列

The corresponding slot function:

// 获取点击的按钮
QPushButton* Obj = qobject_cast<QPushButton*>(this->sender());
if (Obj == nullptr)
{
    
    
    return;
}
QModelIndex qIndex = ui->tableWidget->indexAt(QPoint(Obj->parentWidget()->frameGeometry().x(), Obj->parentWidget()->frameGeometry().y()));
// 获取按钮所在的行和列
int row = qIndex.row();
int column = qIndex.column();

It is basically the same as other codes, it is to be modified to obtain the position of the parent form, namely Obj->parentWidget()->frameGeometry().x(), Obj->parentWidget()->frameGeometry().y() , so that the row and column of the table where the button is located can be correctly obtained.
Summary: If you don’t have any additional operations when you add buttons, you can directly use the top code to get the correct position, but if you add a layout, you need to modify it to the position of the parent control. I hope you can remind some friends , save some time to eat hot pot! ! ! !

Guess you like

Origin blog.csdn.net/qq_41750806/article/details/115370956