QTableWidget项获取窗口小部件类型并访问它

时间:2014-04-07 16:40:12

标签: c++ qt qtablewidget

我试图在QtableWidget中对行进行求和,并且在这样做时我得到了分段错误,不知道是什么导致了这一点,但我认为这与我将单元格小部件项目设置为旋转框的事实有关我没有正确访问它们。 当我在cellChanged事件中设置旋转框时,我也无法触发totalRow函数。

totalRow函数(当单元格被更改时,假定总行数)

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函数(这是将表项设置为spinbox的原因)

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事件

void MainWindow::on_tblScores_cellChanged(int row, int column)
{
    totalRow(row);
}

1 个答案:

答案 0 :(得分:3)

如上所述,使用cellWidget找到解决方案。

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;
}