我有一个QTabWidget,每个标签都包含一个QTableView。 tableviews使用QTableModels从sqlite数据库中读取数据。
模型被保存为成员变量,因此我认为这不是范围问题(这是我通过搜索问题找到的最常见的问题)。
其他数据库操作有效:我尝试在代码中填充/创建表,并正确执行这些操作。
以下是类定义:
#include <QMainWindow>
#include <QtSql>
#include <QString>
namespace Ui {
class MainWindow;
}
class AlisnagMainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit AlisnagMainWindow(QWidget *parent = 0);
~AlisnagMainWindow();
protected:
bool createDB(const QString& filename);
bool loadDB(const QString& filename);
protected slots:
void newFile();
void openFile();
void addRow();
private:
void initModels();
Ui::MainWindow *ui;
QSqlDatabase db;
QSqlRelationalTableModel *loans_model;
QSqlTableModel *people_model;
QSqlRelationalTableModel *items_model;
};
这是构造函数:
AlisnagMainWindow::AlisnagMainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
loans_model( new QSqlRelationalTableModel(this) ),
people_model( new QSqlTableModel(this) ),
items_model( new QSqlRelationalTableModel(this) )
{
ui->setupUi(this);
db = QSqlDatabase::addDatabase("QSQLITE");
connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile()));
connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFile()));
}
这是我初始化模型和视图的方式:
void AlisnagMainWindow::initModels(){
people_model->setTable("people");
people_model->setEditStrategy(QSqlTableModel::OnRowChange);
people_model->select();
people_model->setHeaderData(0, Qt::Horizontal, tr("Name"));
people_model->setHeaderData(1, Qt::Horizontal, tr("Surname"));
people_model->setHeaderData(2, Qt::Horizontal, tr("Phone"));
people_model->setHeaderData(3, Qt::Horizontal, tr("Address"));
items_model->setTable("items");
items_model->setEditStrategy(QSqlTableModel::OnRowChange);
items_model->setRelation(3, QSqlRelation("categories","id","name"));
items_model->select();
loans_model->setTable("loans");
loans_model->setEditStrategy(QSqlTableModel::OnRowChange);
loans_model->setRelation(0, QSqlRelation("items","id","name"));
loans_model->setRelation(1, QSqlRelation("people","id","name"));
loans_model->select();
ui->peopleView->setModel(people_model);
ui->peopleView->hideColumn(0);
ui->itemsView->setModel(items_model);
ui->itemsView->hideColumn(0);
ui->loansView->setModel(loans_model);
ui->loansView->hideColumn(0);
}
数据库按如下方式加载:
bool AlisnagMainWindow::loadDB(const QString &filename)
{
if(db.isOpen())
db.close();
db.setDatabaseName(filename);
if( !db.open() ){
QMessageBox::critical(this, tr("Error"),
tr("Could not open db %1").arg(filename),
QMessageBox::Ok);
return false;
}
ui->statusBar->showMessage("DB successfully opened!");
return true;
}
然后这就是如何组合:
void AlisnagMainWindow::openFile()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Choose DB file"),
".", "*.db");
loadDB(filename);
initModels();
}
我打开的文件已在外部填充。当我运行代码时,既不显示数据也不显示标题。有什么见解吗?
提前致谢。
编辑:根据要求添加了一些上下文
答案 0 :(得分:1)
正如Greenflow指出的那样,问题出在构造函数中,特别是初始化顺序 构造函数修改如下
sorted=1,2,3
1* (2^0 - 2^2) + 2*(2^1 - 2^1) + 3*(2^2 - 2^0) =
1*(-3) + 2*0 + 3*(3) = -3 + 0 + 9 = 6