insert one row and display tow rows in qtableview, with an additional blank row, that's why?

  • 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 also 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!

    binding model

    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        model = new CustomModel(this);
        connect(ui->actionAddItem, &QAction::triggered, this, &MainWindow::onAddCustom);

    when click a button

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

    It is the code inserting one row

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

  • Hi,
    Parameters you pass to beginInsertRows are wrong. They should be left first and right last index positions after your insert is done. For example if you have 0 items and you insert 1 item, in resulting model will have 1 item who's index is 0. In your function you say it is 1. Therefore view think now you insert two rows 0 and 1

  • @asanka424 it works, thanks for you help.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.