Insert record to QSqlTableModel with QListView



  • Hello, I am trying to insert a record to my SQLITE Data Base inserting a row in a QListView widget that has a QSqlTableModel from my Data Base, but I'm having problems.

    My Data Base is something like:

    @CREATE TABLE cd(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title VARCHAR( 30 ) NOT NULL,
    artistid INTEGER NOT NULL,
    FOREIGN KEY ( centro ) REFERENCES centros ( id )
    );@

    Then I create the model and then start the view to see title from the table cd:

    @QSqlTableModel *model = new QSqlTableModel;
    model->setTable("cd");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->setSort(1, Qt::AscendingOrder);
    model->select();

    connect(model, SIGNAL(beforeInsert(QSqlRecord&)), this, SLOT(beforeInsertItem(QSqlRecord&)));

    ui->listview->setModel(model);
    ui->listview->setModelColumn(1);@

    I connected the model to a SLOT for editing de record before insert. To insert a record, I created an other SLOT:

    @void MyListView::addrowClicked()
    {
    model->insertRow(0);
    QModelIndex index = model->index(0, 1);
    ui->listview->setCurrentIndex(index);
    ui->listview->edit(index);
    }@

    and the SLOT beforInsert is:

    @void MyListView::beforeInsertItem(QSqlRecord&)
    {
    record.setValue("artistid", 3);
    }@

    Why the record isn't inserted to the database? I don't understand.

    Thanks any for help!



  • Hi
    What is
    @modulos->getSoporte()@



  • sorry it's a copy-paste error, I edit it now.

    It would be

    @ui->listview->setModel(model);@



  • Your table not alow null value for "title", try insert new row with some info:
    @void MyListView::beforeInsertItem(QSqlRecord&)
    {
    record.setValue("title", QString("type name here..."));
    record.setValue("artistid", 3);
    }@


Log in to reply
 

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