PDA

View Full Version : why insert one row and display tow rows, with an additional blank row?



helloqt
13th February 2016, 04:03
hello everyone,

yesterday, i wrote a test programe using QTableView. i define class CustomModel inheriting from QAbstractTableModel , which implemented rowCount, columnCount, data and headerData. the CustomModel has a member customs storing the data, its a QList. i add a button to add one item to the data.

But when i click the button, the view shows tow columns, one is the item i add, the other is a blank row.

i can't solve it, thanks for your help!


its the initial state
11699

when i click once
11698

when i click twice
11700

CustomModel definition


struct Custom{
Custom();
QString col1;
QString col2;
QString col3;
QString col4;
};

class CustomModel : public QAbstractTableModel{
Q_OBJECT
public:
CustomModel(QObject* parent = 0);
~CustomModel();
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
bool appendCustom(Custom* custom, const QModelIndex &parent = QModelIndex());
private:
QList<Custom*> customs;
};

CustomModel::appendCustom


bool CustomModel::appendCustom(Custom *custom, const QModelIndex &parent)
{
beginInsertRows(parent, customs.count(), customs.count()+1);
customs.append(custom);
endInsertRows();
return true;
}

MainWindow

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

model = new CustomModel(this);
ui->tableView->setModel(model);

connect(ui->actionAddItem, &QAction::triggered, this, &MainWindow::onAddCustom);
}
onAddCustom

void MainWindow::onAddCustom()
{
Custom* new_custom = new Custom();

model->appendCustom(new_custom);
}

anda_skoa
13th February 2016, 11:40
You tell beginInsertRows() that you are adding two rows.

The two integers are the index of the first row to be inserted and the index of the last row to be inserted.
So when inserting one row, those two values need to be the same.

Cheers,
_