这里以checkbox为例:
基本思路:使用槽函数监听checkBox的改变,获取点击checkBox所在的行数和列数文章来源:https://www.toymoban.com/news/detail-753683.html
//设置表头信息
void SystemMngForm::initNetConfigTableAttr()
{
ui->tableWidget->setWordWrap(true);
ui->tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
ui->tableWidget->verticalHeader()->hide();
fileItem = new QTableWidgetItem(QString(""));
ui->tableWidget->setHorizontalHeaderItem(0, fileItem);
fileItem = new QTableWidgetItem(tr(u8"名称"));
ui->tableWidget->setHorizontalHeaderItem(1, fileItem);
fileItem = new QTableWidgetItem(tr(u8"地址"));
ui->tableWidget->setHorizontalHeaderItem(2, fileItem);
fileItem = new QTableWidgetItem(tr(u8"checkBox"));
ui->tableWidget->setHorizontalHeaderItem(3, fileItem);
ui->tableWidget->setAutoScroll(true);
//每个元素居中
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
//单个选择
ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
//失去焦点
ui->tableWidget->setFocusPolicy(Qt::NoFocus);
//自适应表头
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
//显示数据,里面有checkBox控件嵌套
void SystemMngForm::showNetConfigInfo()
{
ui->tableWidget->setColumnCount(8);
ui->tableWidget->setRowCount(2);
for(int i = 0; i < 2; i++)
{
item = new QTableWidgetItem(QString(""));
ui->tableWidget->setItem(i, 0, item);
item = new QTableWidgetItem(u8"网口");
item->setTextAlignment(Qt::AlignCenter);
ui->tableWidget->setItem(i, 1, item);
item = new QTableWidgetItem(u8"127.0.0.1");
item->setTextAlignment(Qt::AlignCenter);
ui->tableWidget->setItem(i, 2, item);
checkBoxWidget= new Widget;
checkBoxLayout = new QHBoxLayout();
checkBox = new QCheckBox();
checkBoxLayout ->addWidget(checkBox);
//一定要设置为0,否则很难看
checkBoxLayout->setMargin(0);
checkBoxLayout->setAlignment(checkBox, Qt::AlignCenter);
checkBoxWidget->setLayout(checkBoxLayout);
ui->tableWidget->setCellWidget(i, 3, checkBoxWidget);
//槽函数,stateChange(int)为checkBox的信号
connect(checkBox, SIGNAL(stateChange(int)), this, SLOT(checkBoxChange(int));
}
initNetConfigTableAttr();
}
槽函数文章来源地址https://www.toymoban.com/news/detail-753683.html
void SystemMngForm::checkBoxChange(int)
{
//全局变量,行和列
checkBoxRow = 0;
checkBoxColumn = 0;
//
QCheckBox *checkBox = dynamic_cast<QCheckBox *>(this->sender());
if(checkBox = nullptr)
return;
//坐标转换获取坐标
int x = checkBox->parentWidget()->frameGeometry().x();
int y = checkBox->parentWidget()->frameGeometry().y();
QModelIndex index = ui->tableWidget->indexAt(QPoint(x, y));
int row = index.row();
int column = index.column();
qDebug()<<"row"<<row<<"column"<<column;
//通过row、column找到控件
QWidget *wig = ui->tableWidget->cellWidget(row, column);
checkBox = wig->findChild<QCheckBox *>();
if(checkBox->isChecked())
{
checkBoxRow = row;
checkBoxColumn = column;
qDebug)<<"checkBoxRow"<<checkBoxRow<<"checkBoxColumn"<<checkBoxColumn;
}
}
到了这里,关于关于在Qt中tableWidget表格中有按钮或者chebox选择点击事件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!