我的同事发现了QSqlTableModel的下一个问题:

#define VARIANT_1
class SomeClass : public QWidget
{
    Q_OBJECT

public:

SomeClass(QWidget *parent = 0, Qt::WFlags flags = 0)
{
    ui.setupUi(this);

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if (!db.open()) {
        return;
    }

    QSqlQuery query;
    query.exec("create table person (id int primary key, "
               "firstname varchar(20), lastname varchar(20))");
    query.exec("insert into person values(101, 'Danny', 'Young')");
    query.exec("insert into person values(102, 'Christine', 'Holand')");

#if defined( VARIANT_1 )
    p_model = new QSqlTableModel( );
    QSqlTableModel & model = *p_model;
#endif
    model.setTable("person");
    model.setEditStrategy(QSqlTableModel::OnManualSubmit);
    model.select();

    model.setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
    model.setHeaderData(1, Qt::Horizontal, QObject::tr("First name"));
    model.setHeaderData(2, Qt::Horizontal, QObject::tr("Last name"));

    ui.tableView->setModel(&model);

}

private:
    Ui::qhlbClass ui;
    QSqlDatabase db;
#if defined( VARIANT_1 )
    QSqlTableModel * p_model;
#else
    QSqlTableModel model;
#endif
};


如果定义了VARIANT_1,tableView将显示右表,否则-不会。
即如果QSqlTableModel出现在对象表未显示其数据的情况下...
如果QSqlTableModel用作指针,则可以正常工作...
你能对此发表评论吗?

最佳答案

QSqlTableModel构造函数

QSqlTableModel ( QObject * parent = 0, QSqlDatabase db = QSqlDatabase() )


需要一个QSqlDatabase连接,该连接在构造model成员时不可用。

    QSqlDatabase db; // <-- not set
#if defined( VARIANT_1 )
    QSqlTableModel * p_model;
#else
    QSqlTableModel model; // default db isn't set
#endif


但在这里

db = QSqlDatabase::addDatabase("QSQLITE"); // a connection is set up
db.setDatabaseName(":memory:");
if (!db.open()) {
    return;
}
. . .
#if defined( VARIANT_1 )
    p_model = new QSqlTableModel( ); // <-- a default connection exists
    QSqlTableModel & model = *p_model;

关于qt - QSqlTableModel不能用作对象,但可以用作指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6587158/

10-08 22:38