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
struct Custom{
Custom();
};
Q_OBJECT
public:
~CustomModel();
QVariant headerData
(int section, Qt
::Orientation orientation,
int role
) const;
private:
QList<Custom*> customs;
};
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;
};
To copy to clipboard, switch view to plain text mode
CustomModel::appendCustom
bool CustomModel
::appendCustom(Custom
*custom,
const QModelIndex &parent
) {
beginInsertRows(parent, customs.count(), customs.count()+1);
customs.append(custom);
endInsertRows();
return true;
}
bool CustomModel::appendCustom(Custom *custom, const QModelIndex &parent)
{
beginInsertRows(parent, customs.count(), customs.count()+1);
customs.append(custom);
endInsertRows();
return true;
}
To copy to clipboard, switch view to plain text mode
MainWindow
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);
}
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);
}
To copy to clipboard, switch view to plain text mode
onAddCustom
void MainWindow::onAddCustom()
{
Custom* new_custom = new Custom();
model->appendCustom(new_custom);
}
void MainWindow::onAddCustom()
{
Custom* new_custom = new Custom();
model->appendCustom(new_custom);
}
To copy to clipboard, switch view to plain text mode
Bookmarks