QString name=ui->namelineEdit->text();//收件人姓名
//tel=ui->tellineEdit->text();//获取电话信息
QString danhao=ui->numlineEdit->text();//获取单号信息
//QSqlQueryModel *model = new QSqlQueryModel;
QSqlQueryModel *model = new QSqlQueryModel(ui->tableView);
model->setQuery("select *from thing where thing.thing_id='"+danhao+"' "
"and thing.recive_pho='"+name+"'");
model->setHeaderData(0, Qt::Horizontal, tr("订单号"));
model->setHeaderData(1, Qt::Horizontal, tr("收件人"));
model->setHeaderData(2, Qt::Horizontal, tr("寄件人"));
model->setHeaderData(3, Qt::Horizontal, tr("验证码"));
model->setHeaderData(4, Qt::Horizontal, tr("箱子号"));
model->setHeaderData(5, Qt::Horizontal, tr("物品状态"));
//qDebug()<<name<<danhao;
ui->tableView->setModel(model);
//ui->tableView->show();
看了评论以后,做了一些修改,将完整的demo发布上来。
1、连接数据库
void MainWindow::linkSlot()//连接数据库
{
// 创建数据库连接的这些信息在实际开发的时都需要通过读取配置文件得到,
QSettings *configIniRead = new QSettings("swxctx.ini", QSettings::IniFormat);
//将读取到的ini文件保存在QString中,先取值,然后通过toString()函数转换成QString类型
QString ipResult = configIniRead->value("/ip/first").toString();
QString userResult = configIniRead->value("/user/first").toString();
QString passResult = configIniRead->value("/pass/first").toString();
QString dataResult = configIniRead->value("/ku/first").toString();
//读入完成后删除指针
delete configIniRead;
/*加载数据库驱动并且进行连接*/
this->db=QSqlDatabase::addDatabase("QMYSQL");//加载驱动
this->db.setHostName(""+ipResult+"");//本地连接
this->db.setUserName(""+userResult+"");//root用户
this->db.setPassword(""+passResult+"");//mysql密码
this->db.setDatabaseName(""+dataResult+"");//需要连接的数据库
bool ok=db.open();//打开
if(ok)
{
QMessageBox::information(this,"Good","连接成功.");
}
else
{
QMessageBox::information(this,"Error","请检查是否存在问题.");
}
}
2、查询数据显示到tableview
void MainWindow::selectBoxSlot()//查询箱子状态
{
bool ok=db.open();
if(ok)
{
QSqlQueryModel *model = new QSqlQueryModel(ui->tableView);
model->setQuery(QString("select box_id,case box_state when 1 then '待取' "
"else '已取' end as box_state,case box_size when 1 "
"then '大' when 2 then '中' else '小' end as box_size "
"from box;"));
//列名
model->setHeaderData(0, Qt::Horizontal, tr("ID"));
model->setHeaderData(1, Qt::Horizontal, tr("状态"));
model->setHeaderData(2, Qt::Horizontal, tr("型号"));
ui->tableView->setModel(model);//数据放置进去
ui->tableView->verticalHeader()->hide();//不显示序号
}
else
{
QMessageBox::warning(this,"错误","未连接,请检查.");
}
}
在这里因为我还有后续操作,所以并没有关闭数据库连接,正常来说在这里是需要关闭数据库连接的。
3、在MainWindow引入
//查询箱子状态
QObject::connect(ui->boxpushButton,SIGNAL(clicked()),this,SLOT(selectBoxSlot()));
//菜单
//连接数据库
QObject::connect(ui->linkaction,SIGNAL(triggered()),this,SLOT(linkSlot()));
页面内有一个菜单连接数据库,同时存在一个tableview,还有一个按钮boxpushbutton,点击按钮box即可将查询到的数据在tableview显示。