QTableWidget Item 获取小部件类型并访问它 [英] QTableWidget Item Get Widget Type and Access It
问题描述
我正在尝试对 QtableWidget 中的行求和,但我在这样做时遇到了分段错误,不确定是什么原因造成的,但我认为这与我将单元格小部件项目设置为旋转框和我没有正确访问它们.当我在 cellChanged 事件中设置它时,我也无法在旋转框更改时触发 totalRow 函数.
I am attempting to sum rows in a QtableWidget and I get a segmentation fault when doing so not sure what is causing this, but I think it has something to do with the fact that I am setting the cell widget items as spinboxes and I am not accessing them correctly. I also am unable to get the totalRow function to fire when the spin box changes, when I set it in the cellChanged event.
totalRow 函数(假设在单元格改变时计算行)
totalRow Function (Supposed To Total The Row When A Cell Is Changed)
int MainWindow::totalRow(int srow)
{
int sum = 0;
int num_col = ui->tblScores->columnCount();
int num_row = ui->tblScores->rowCount();
for (int j = 0; j < num_col - 1 ; ++j) {
QTableWidgetItem *tableItem = ui->tblScores->item(srow,j);
sum += tableItem->text().toInt();
cout << sum << endl;
}
QTableWidgetItem *tableItem = new QTableWidgetItem;
tableItem->setText(QString::number(sum));
ui->tblScores->setItem(srow,num_col - 1,tableItem);
return sum;
}
setupTable 函数(这是将表格项设置为旋转框的方法)
setupTable Function (This is what sets the table items to spinboxes)
void MainWindow::setupTable()
{
int num_col = ui->tblScores->columnCount();
int num_row = ui->tblScores->rowCount();
for (int i = 0; i < num_row; ++i) {
for (int j = 0; j < num_col - 1 ; ++j) {
ui->tblScores->setCellWidget(i,j,new QSpinBox(ui->tblScores));
}
ui->tblScores->setCellWidget(i,num_col - 1,new QLabel(ui->tblScores));
}
}
cellChanged 事件
cellChanged Event
void MainWindow::on_tblScores_cellChanged(int row, int column)
{
totalRow(row);
}
推荐答案
按照上述建议使用 cellWidget 找到了解决方案.
Found the solution with cellWidget as suggested above.
int MainWindow::totalRow(int srow)
{
int sum = 0;
int num_col = ui->tblScores->columnCount();
for(int j = 0; j < num_col - 1 ; j++) {
QSpinBox* sp;
sp = (QSpinBox*)ui->tblScores->cellWidget(srow,j);
sum = sum + sp->value();
}
QTableWidgetItem *tableItem = new QTableWidgetItem;
tableItem->setText(QString::number(sum));
ui->tblScores->setItem(srow,num_col - 1,tableItem);
return sum;
}
这篇关于QTableWidget Item 获取小部件类型并访问它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!