[solved] QSqlTableModel not showing in QTableView



  • class Sql
    sql.h
    @
    public:
    QSqlTableModel* getCiselnikydata(QString type);
    @

    sql.cpp
    @
    QSqlTableModel* Sql::getCiselnikydata(QString type)
    {
    QSqlTableModel *ciselnikyDataModel = new QSqlTableModel(this,db);
    ciselnikyDataModel->setTable("ciselniky");
    ciselnikyDataModel->select();
    qDebug() << ciselnikyDataModel->lastError().text();
    return ciselnikyDataModel;
    }
    @

    class CiselnikyOkno
    ciselnikyokno.h
    @
    private:
    QSqlTableModel *data;

    private slots:
    void showData(int row);
    @

    ciselnikyokno.cpp
    @
    void CiselnikyOkno::showData(int row)
    {
    if (row >= 0) {
    Sql sql;
    if (sql.connect()) {
    data = sql.getCiselnikydata(ui->type->currentText());
    ui->table->setModel(data);
    }
    }
    }
    @

    The problem is that nothing shows in my QTableView (ui->table)


  • Lifetime Qt Champion

    Hi,

    Maybe a silly question but, are you sure there's something in the table ?



  • Hi,

    i have data in the table and no error shows
    qDebug() << ciselnikyDataModel->lastError().text();


  • Lifetime Qt Champion

    Ok, then also check the row/column count of your model to ensure there's something in it



  • i have added this code
    @
    qDebug() << ciselnikyDataModel->rowCount();
    qDebug() << ciselnikyDataModel->columnCount();
    @

    after the line
    @
    qDebug() << ciselnikyDataModel->lastError().text();
    @

    in sql.cpp. it returns me that i have 10 rows and 4 columns, the same as in the database


  • Lifetime Qt Champion

    Found it:

    @QSqlTableModel *ciselnikyDataModel = new QSqlTableModel(this,db);@

    You are giving your model a parent here however, your Sql object gets destroyed before the end of showData which in turns deletes the model and thus you won't have anything to show.



  • So the solution is to add this line into ciselnikyokno.h
    @
    Sql *sql;
    @

    and this line into ciselniky.cpp
    @
    sql = new Sql(this);
    @

    It works for me, but I have one question.
    Have I done it correct?


  • Lifetime Qt Champion

    You can simply not set the model parent when constructing it


Log in to reply
 

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