3 Attachment(s)
why insert one row and display tow rows, with an additional blank row?
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!
CustomModel definition
Code:
struct Custom{
Custom();
};
Q_OBJECT
public:
~CustomModel();
QVariant headerData
(int section, Qt
::Orientation orientation,
int role
) const;
private:
QList<Custom*> customs;
};
CustomModel::appendCustom
Code:
bool CustomModel
::appendCustom(Custom
*custom,
const QModelIndex &parent
) {
beginInsertRows(parent, customs.count(), customs.count()+1);
customs.append(custom);
endInsertRows();
return true;
}
MainWindow
Code:
MainWindow
::MainWindow(QWidget *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
Code:
void MainWindow::onAddCustom()
{
Custom* new_custom = new Custom();
model->appendCustom(new_custom);
}
Re: why insert one row and display tow rows, with an additional blank row?
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,
_