sqlite - Qt/QTableView/SQLite如何连接?

标签 sqlite qt qtableview

这是我第一次Qt编程。我要在关系数据库上制作一个地址簿,以跟踪与个人和公司相关的电话和事件。一个简单的自制销售工具。我非常需要它。

使用 Qt Designer 我创建了一个主窗口并放置了一个 QTableView 小部件。安装SQLite,创建数据库。现在我需要将其连接到QTableView。我花了好几个小时,还是没能做到。

有人可以帮忙吗?

谢谢!

一些代码:

untitled9.pro:

#-------------------------------------------------
#
# Project created by QtCreator 2012-10-26T14:35:12
#
#-------------------------------------------------

QT       += core gui
QT       += sql

TARGET = untitled9
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_menu_exit_triggered();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

main.cpp:

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QTableView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    w.show();

    QTableView *tableView;

    return a.exec();
}

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_menu_exit_triggered()
{
  QCoreApplication::quit ();
}

并且,mainwindow.ui 中还有一个很长的 xml。如果需要的话我会把它发布在这里。

谢谢!

最佳答案

您应该检查 model-view related Qt documentation .

一般来说,您需要一个与数据库表相对应的 [QSqlTableModel][2]。然后您只需将其附加到 TableView 即可。

// Let a table A, with the following columns : id, column1, column2
QSqlTableModel *model = new QSqlTableModel(parentObject, database);
model->setTable("A");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
model->removeColumn(0); // don't show the ID
model->setHeaderData(0, Qt::Horizontal, tr("Column 1"));
model->setHeaderData(1, Qt::Horizontal, tr("Column 2"));

// Attach it to the view
ui->view->setModel(model);

关于sqlite - Qt/QTableView/SQLite如何连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13099830/

相关文章:

c++ - 如何在 Qt 中的 QTableView 中显示一个简单的 QMap?

c++ - C++ 中的 SQLite。数据库正忙(多线程)

sqlite - 在 Valentina Studio 中创建表错误

c++ - 根据比例更改 QProgressbar block 的颜色

c++ - 复制文件进度条

qt - 在 QTableView 列中显示 QAbstractListModel 项目

QTableView 似乎没有对 dataChanged 信号使用react

iphone - 如何在 iPhone 上打开加密的 SQLITE 数据库?

python - 无法找到: ERROR [root] Error: Can't locate revision identified by '..' 的来源

c++ - 使用 libssl/libcrypto 的段错误