目录
1. 主界面布局
先创建一个QMainwindow,不带设计界面
cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGroupBox>
#include <QTableView>
#include <QListWidget>
#include <QLabel>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
//MainWindow(QWidget *parent = 0);
MainWindow(QWidget *parent = 0); //构造函数
~MainWindow();
private:
QGroupBox *createCarGroupBox();
QGroupBox *createFactoryGroupBox();
QGroupBox *createDetailsGroupBox();
void createMenuBar();
QTableView *carView; //(a)
QTableView *factoryView; //(b)
QListWidget *attribList; //显示车型的详细信息列表
/* 声明相关的信息标签 */
QLabel *profileLabel;
QLabel *titleLabel;
};
#endif // MAINWINDOW_H
然后再在mainwindow.cpp中
cpp
#include "mainwindow.h"
#include <QGridLayout>
#include <QAbstractItemView>
#include <QHeaderView>
#include <QAction>
#include <QMenu>
#include <QMenuBar>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QGroupBox *factory = createFactoryGroupBox();
QGroupBox *cars = createCarGroupBox();
QGroupBox *details = createDetailsGroupBox();
//布局
QGridLayout *layout = new QGridLayout;
layout->addWidget(factory, 0, 0);
layout->addWidget(cars, 1, 0);
layout->addWidget(details, 0, 1, 2, 1);
layout->setColumnStretch(1, 1);
layout->setColumnMinimumWidth(0, 500);
QWidget *widget = new QWidget;
widget->setLayout(layout);
setCentralWidget(widget);
createMenuBar();
resize(850, 400);
setWindowTitle(u8"主从视图");
}
QGroupBox* MainWindow::createFactoryGroupBox()
{
factoryView = new QTableView;
factoryView->setEditTriggers(QAbstractItemView::NoEditTriggers);
//(a)
factoryView->setSortingEnabled(true);
factoryView->setSelectionBehavior(QAbstractItemView::SelectRows);
factoryView->setSelectionMode(QAbstractItemView::SingleSelection);
factoryView->setShowGrid(false);
factoryView->setAlternatingRowColors(true);
QGroupBox *box = new QGroupBox(u8"汽车制造商");
QGridLayout *layout = new QGridLayout;
layout->addWidget(factoryView, 0, 0);
box->setLayout(layout);
return box;
}
QGroupBox* MainWindow::createCarGroupBox()
{
QGroupBox *box = new QGroupBox(u8"汽车");
carView = new QTableView;
carView->setEditTriggers(QAbstractItemView::NoEditTriggers);
carView->setSortingEnabled(true);
carView->setSelectionBehavior(QAbstractItemView::SelectRows);
carView->setSelectionMode(QAbstractItemView::SingleSelection);
carView->setShowGrid(false);
carView->verticalHeader()->hide();
carView->setAlternatingRowColors(true);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(carView, 0, 0);
box->setLayout(layout);
return box;
}
QGroupBox* MainWindow::createDetailsGroupBox()
{
QGroupBox *box = new QGroupBox(u8"详细信息");
profileLabel = new QLabel;
profileLabel->setWordWrap(true);
profileLabel->setAlignment(Qt::AlignBottom);
titleLabel = new QLabel;
titleLabel->setWordWrap(true);
titleLabel->setAlignment(Qt::AlignBottom);
attribList = new QListWidget;
QGridLayout *layout = new QGridLayout;
layout->addWidget(profileLabel, 0, 0, 1, 2);
layout->addWidget(titleLabel, 1, 0, 1, 2);
layout->addWidget(attribList, 2, 0, 1, 2);
layout->setRowStretch(2, 1);
box->setLayout(layout);
return box;
}
void MainWindow::createMenuBar()
{
QAction *addAction = new QAction(u8"添加", this);
QAction *deleteAction = new QAction(u8"删除", this);
QAction *quitAction = new QAction(u8"退出", this);
addAction->setShortcut(tr("Ctrl+A"));
deleteAction->setShortcut(tr("Ctrl+D"));
quitAction->setShortcut(tr("Ctrl+Q"));
QMenu *fileMenu = menuBar()->addMenu(u8"操作菜单");
fileMenu->addAction(addAction);
fileMenu->addAction(deleteAction);
fileMenu->addSeparator();
fileMenu->addAction(quitAction);
}
MainWindow::~MainWindow()
{
}
运行结果如图所示
2.连接数据库
改个名字项目结构更清晰一点
这边需要先添加最底层的GroupBox控件,数据库连接设置,再在上面添加别的
添加完控件之后需要将.ui文件生成.h文件
此处转换方法参考
cpp
uic connectdlg.ui -o ui_connectdlg.h
头文件connectdlg.h中
cpp
#ifndef CONNECTDLG_H
#define CONNECTDLG_H
#include <QDialog>
#include <QMessageBox>
#include "ui_connectdlg.h"
class QSqlError;
class ConnDlg : public QDialog
{
Q_OBJECT
public:
ConnDlg(QWidget *parent = 0);
//~ConnDlg();
QString driverName() const;
QString databaseName() const;
QString userName() const;
QString password() const;
QString hostName() const;
int port() const;
QSqlError addConnection(const QString &driver, const QString &dbName, const QString &host,const QString &user, const QString &passwd, int port = -1);
void creatDB();
void addSqliteConnection();
private slots:
void on_okButton_clicked();
void on_cancelButton_clicked() { reject(); }
void driverChanged(const QString &);
private:
Ui::QSqlConnectionDialogUi ui;
};
#endif // CONNECTDLG_H
connectdlg.cpp中
cpp
#include "connectdlg.h"
#include "ui_connectdlg.h"
#include <QSqlDatabase>
#include <QtSql>
#pragma execution_character_set("UTF-8")
ConnDlg::ConnDlg(QWidget *parent) :
QDialog(parent)
{
ui.setupUi(this);
QStringList drivers = QSqlDatabase::drivers(); //(a)
ui.comboDriver->addItems(drivers); //(b)
connect(ui.comboDriver,SIGNAL(currentIndexChanged(const QString &)),this,SLOT(driverChanged(const QString &))); //(c)
ui.status_label->setText(u8"准备连接数据库!"); //(d)
}
/*
ConnDlg::~ConnDlg()
{
delete ui;
}
*/
void ConnDlg::driverChanged(const QString & text)
{
if(text =="QSQLITE") //(a)
{
ui.editDatabase->setEnabled(false);
ui.editUsername->setEnabled(false);
ui.editPassword->setEnabled(false);
ui.editHostname->setEnabled(false);
ui.portSpinBox->setEnabled(false);
}
else
{
ui.editDatabase->setEnabled(true);
ui.editUsername->setEnabled(true);
ui.editPassword->setEnabled(true);
ui.editHostname->setEnabled(true);
ui.portSpinBox->setEnabled(true);
}
}
QString ConnDlg::driverName() const
{
return ui.comboDriver->currentText();
}
QString ConnDlg::databaseName() const
{
return ui.editDatabase->text();
}
QString ConnDlg::userName() const
{
return ui.editUsername->text();
}
QString ConnDlg::password() const
{
return ui.editPassword->text();
}
QString ConnDlg::hostName() const
{
return ui.editHostname->text();
}
int ConnDlg::port() const
{
return ui.portSpinBox->value();
}
void ConnDlg::on_okButton_clicked()
{
if (ui.comboDriver->currentText().isEmpty()) //(a)
{
ui.status_label->setText(u8"请选择一个数据库驱动!");
ui.comboDriver->setFocus();
}
else if(ui.comboDriver->currentText() =="QSQLITE") //(b)
{
addSqliteConnection();
//创建数据库表,如已存在则无须执行
creatDB(); //(c)
accept();
}
else
{
QSqlError err = addConnection(driverName(), databaseName(), hostName(),userName(), password(), port()); //(d)
if (err.type() != QSqlError::NoError) //(e)
ui.status_label->setText(err.text());
else //(f)
ui.status_label->setText(u8"连接数据库成功!");
//创建数据库表,如已存在则无须执行
accept();
}
}
QSqlError ConnDlg::addConnection(const QString &driver, const QString &dbName, const QString &host,const QString &user, const QString &passwd, int port)
{
QSqlError err;
QSqlDatabase db = QSqlDatabase::addDatabase(driver);
db.setDatabaseName(dbName);
db.setHostName(host);
db.setPort(port);
if (!db.open(user, passwd)) //(a)
{
err = db.lastError();
}
return err; //返回这个错误信息
}
void ConnDlg::addSqliteConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("databasefile");
if (!db.open())
{
ui.status_label->setText(db.lastError().text());
return;
}
ui.status_label->setText(u8"创建sqlite数据库成功!");
}
void ConnDlg::creatDB()
{
QSqlQuery query; //(a)
query.exec("create table factory (id int primary key,manufactory varchar(40), address varchar(40))"); //(b)
query.exec(QObject::tr("insert into factory values(1, '一汽大众', '长春')"));
query.exec(QObject::tr("insert into factory values(2, '二汽神龙', '武汉')"));
query.exec(QObject::tr("insert into factory values(3, '上海大众', '上海')"));
query.exec("create table cars (carid int primary key, name varchar(50), factoryid int, year int, foreign key(factoryid) references factory(id))"); //(c)
query.exec(QObject::tr("insert into cars values(1,'奥迪A6',1,2005)"));
query.exec(QObject::tr("insert into cars values(2, '捷达', 1, 1993)"));
query.exec(QObject::tr("insert into cars values(3, '宝来', 1, 2000)"));
query.exec(QObject::tr("insert into cars values(4, '毕加索',2, 1999)"));
query.exec(QObject::tr("insert into cars values(5, '富康', 2, 2004)"));
query.exec(QObject::tr("insert into cars values(6, '标致307',2, 2001)"));
query.exec(QObject::tr("insert into cars values(7, '桑塔纳',3, 1995)"));
query.exec(QObject::tr("insert into cars values(8, '帕萨特',3, 2000)"));
}
3.主/从视图应用
完整的mainwindow.h代码
代码太多了,看资源绑定吧
新建一个xml文件
注意,xml文件路径,和python一样的,向右倒的
cpp
#define XML_FILE_PATH "D:/Qt_CH/CH13/CH1302/SQLEx/attribs.xml"
当我新添加一个时,发现xml文件里面也写进去了