1. 程式人生 > 其它 >QTableWidget在單元格中動態新增的控制元件,獲取所在列行

QTableWidget在單元格中動態新增的控制元件,獲取所在列行

最近在使用QTableWidget,碰到了在單元格中動態新增控制元件,如QPushButton、QComboBox等,新增十分簡單,直接使用QTableWidget::setCellWidget(int row, int column, QWidget widget)這一函式就可新增成功,但是怎麼獲取所在行列成了難題。
網上查找了相關方法,大多數都是使用的通過點選該控制元件的方法獲取它的行和列;
按鍵對應的槽函式:
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();

這樣就獲取當前的行和列了,但是我獲取到的全是0行0列,而且很多評論區的小夥伴也遇到了同樣的問題,仔細分析了一下,問題出現在新增按鍵上,因為我需要新增的是兩個按鍵,所以加了個佈局以及 QWidget* btns = new QWidget(this);,這樣獲取的始終是在按鍵這個btns中的位置,所以一直都是0,0。

效果圖:
在這裡插入圖片描述

直接看修正後的完整程式碼:
新增按鍵程式碼:

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列

對應的槽函式:

// 獲取點選的按鈕
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();

與其他程式碼基本相同,就是要修改為獲取父類窗體的位置,即Obj->parentWidget()->frameGeometry().x(),Obj->parentWidget()->frameGeometry().y(),這樣就可正確獲取按鍵所在表格的行列了。
總結:如果小夥伴新增按鍵時無任何附加操作,可直接用最上面的程式碼就可獲取正確的位置,但是如果加入了佈局,就需要修改為父類控制元件的位置,希望可以提醒到一些小夥伴,省下一些時間吃火鍋!!!!