very simple example
h
#ifndef TEST_H
#define TEST_H
#include <QMainWindow>
{
Q_OBJECT
public:
private slots:
private:
};
#endif//TEST_H
#ifndef TEST_H
#define TEST_H
#include <QMainWindow>
class QTableWidget;
class QTableWidgetItem;
class Test: public QMainWindow
{
Q_OBJECT
public:
Test(QWidget *parent = 0);
private slots:
void recalculateSums(QTableWidgetItem *);
private:
QTableWidget *m_table;
};
#endif//TEST_H
To copy to clipboard, switch view to plain text mode
cpp
#include <QtGui>
#include "test.h"
{
for (int row = 0; row < m_table->rowCount(); ++row) {
for (int column = 0; column < m_table->columnCount(); ++column) {
tableItem
->setText
(QString::number(row
));
m_table->setItem(row, column, tableItem);
}
}
const int lastRow = m_table->rowCount();
m_table->setRowCount(lastRow + 1);
for (int column = 0; column < m_table->columnCount(); ++column)
item->setText(tr("Sum"));
m_table->setVerticalHeaderItem(lastRow, item);
setCentralWidget(m_table);
}
{
const int lastRow = m_table->rowCount() - 1;
if (item && item->row() == lastRow)
return;
for (int column = 0; column < m_table->columnCount(); ++column) {
int sum = 0;
for (int row = 0; row < lastRow; ++row) {
sum += tableItem->text().toInt();
}
m_table
->item
(lastRow, column
)->setText
(QString::number(sum
));
}
}
#include <QtGui>
#include "test.h"
Test::Test(QWidget *parent)
: QMainWindow(parent)
{
m_table = new QTableWidget(10, 10);
for (int row = 0; row < m_table->rowCount(); ++row) {
for (int column = 0; column < m_table->columnCount(); ++column) {
QTableWidgetItem *tableItem = new QTableWidgetItem;
tableItem->setText(QString::number(row));
m_table->setItem(row, column, tableItem);
}
}
const int lastRow = m_table->rowCount();
m_table->setRowCount(lastRow + 1);
for (int column = 0; column < m_table->columnCount(); ++column)
m_table->setItem(lastRow, column, new QTableWidgetItem);
QTableWidgetItem *item = new QTableWidgetItem;
item->setText(tr("Sum"));
m_table->setVerticalHeaderItem(lastRow, item);
setCentralWidget(m_table);
connect(m_table, SIGNAL(itemChanged(QTableWidgetItem *)), SLOT(recalculateSums(QTableWidgetItem *)));
}
void Test::recalculateSums(QTableWidgetItem *item)
{
const int lastRow = m_table->rowCount() - 1;
if (item && item->row() == lastRow)
return;
for (int column = 0; column < m_table->columnCount(); ++column) {
int sum = 0;
for (int row = 0; row < lastRow; ++row) {
QTableWidgetItem *tableItem = m_table->item(row, column);
sum += tableItem->text().toInt();
}
m_table->item(lastRow, column)->setText(QString::number(sum));
}
}
To copy to clipboard, switch view to plain text mode
Bookmarks