大家好,因为我是Qt的新手,我的问题是我想从Sql数据库中删除已存储的图像,因为我已经在我的Gui中创建了一个删除按钮,它应该就像我按下表中的选择文件一样视图应从数据库中删除以及从tableview中删除。为此,我尽力使它工作,但它没有工作。请帮忙。
// Database.h /// 我已经定义了removedRecord
public slots:
bool insertIntoTable(const QVariantList &data);
bool insertIntoTable(const QString &name, const QByteArray &pic);
bool removeRecord(const int id);
// Database.cpp //
**#include "database.h"**
DataBase::DataBase(QObject *parent) : QObject(parent)
{
}
DataBase::~DataBase()
{
}
void DataBase::connectToDataBase()
{
if(!QFile("../AIC_Data_Base/" DATABASE_NAME).exists()){
this->restoreDataBase();
} else {
this->openDataBase();
}
}
bool DataBase::restoreDataBase()
{
if(this->openDataBase()){
return (this->createTable()) ? true : false;
} else {
qDebug() << "Data Base error";
return false;
}
return false;
}
bool DataBase::openDataBase()
{
db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName(DATABASE_HOSTNAME);
db.setDatabaseName("../AIC_Data_Base/" DATABASE_NAME);
if(db.open()){
return true;
} else {
return false;
}
}
void DataBase::closeDataBase()
{
db.close();
}
bool DataBase::createTable()
{
QSqlQuery query;
if(!query.exec( "CREATE TABLE " TABLE " ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
TABLE_NAME " VARCHAR(255) NOT NULL,"
TABLE_PIC " BLOB NOT NULL"
" )"
)){
qDebug() << "DataBase: error of create " << TABLE;
qDebug() << query.lastError().text();
return false;
} else {
return true;
}
return false;
}
bool DataBase::insertIntoTable(const QVariantList &data)
{
QSqlQuery query;
query.prepare("INSERT INTO " TABLE " ( " TABLE_NAME ", "
TABLE_PIC " ) "
"VALUES (:Name, :Pic)");
query.bindValue(":Name", data[0].toString());
query.bindValue(":Pic", data[1].toByteArray());
if(!query.exec()){
qDebug() << "error insert info " << TABLE;
qDebug() << query.lastError().text();
return false;
} else {
return true;
}
return false;
}
bool DataBase::insertIntoTable(const QString &name, const QByteArray &pic)
{
QVariantList data;
data.append(name);
data.append(pic);
if(insertIntoTable(data))
return true;
else
return false;
}
bool DataBase::removeRecord(const int id)
{
QSqlQuery query;
query.prepare("DELETE FROM " TABLE " WHERE id= :ID ;");
query.bindValue(":ID", id);
if(!query.exec()){
qDebug() << "error delete row " << TABLE;
qDebug() << query.lastError().text();
return false;
} else {
return true;
}
return false;
}
Mainwindow.h
private slots:
void on_pushButton_add_clicked();
void on_screenButton_clicked();
void slotCurrentPic(QModelIndex index);
void on_Delete_Button_clicked(QModelIndex index);
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMainWindow>
#include <QDesktopWidget>
#include <QMessageBox>
#include <QFileInfo>
#include <QString>
#include <QFile>
#include <QFileDialog>
#include <QDir>
#include <QDebug>
#include <QWidget>
#include <QPixmap>
#include <QApplication>
#include <QBuffer>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// this command is used for : setting the title screen and logo.
this->setWindowTitle("AIC Tool V1.0");
setWindowIcon(QIcon(":/9982-200.png"));
db = new DataBase();
db->connectToDataBase();
this->setupModel(TABLE,
QStringList() << trUtf8("id")
<< trUtf8("Picture List")
<< trUtf8("Data_Base")
);
this->createUI();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_add_clicked()
{
QFileDialog dialog(this);
dialog.setNameFilter(tr("*.png *.gif *.jpg *.tif *.xpm"));
dialog.setViewMode(QFileDialog::Detail);
QString fileName =QFileDialog::getOpenFileName(this,tr("Open Image"),"../AIC_Incoming_Images",tr ("Image Files(*.png *.gif *.jpg *.tif *.xpm)"));
ui->label->setText(fileName);
if(!fileName.isEmpty())
{
QImage image(fileName);
int w = ui->label_newpic->width();
int h = ui->label_newpic->height();
QPixmap tasveer =QPixmap::fromImage(image);
ui->label_newpic->setPixmap(tasveer.scaled(w,h,Qt::KeepAspectRatio));
//ui->label_datapic->setPixmap(tasveer.scaled(w,h,Qt::KeepAspectRatio));
}
else {
QMessageBox::critical(this, "Error", "No file selected");
}
}
void MainWindow::setupModel(const QString &tableName, const QStringList &headers)
{
model = new QSqlTableModel(this);
model->setTable(tableName);
/* Set the columns names in a table with sorted data
* */
for(int i = 0, j = 0; i < model->columnCount(); i++, j++){
model->setHeaderData(i,Qt::Horizontal,headers[j]);
}
}
void MainWindow::createUI()
{
ui->tableView->setModel(model);
ui->tableView->setColumnHidden(0, true); // Hide the column id Records
ui->tableView->setColumnHidden(2, true); // Hide the column with image
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->resizeColumnsToContents();
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); // editing is not allowed
ui->tableView->horizontalHeader()->setStretchLastSection(true); // Stretch the last column of around tableView
/* Connect the signal to change the selection of the current row in the table
* to the slot to set the image picLabel
* */
connect(ui->tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
this, SLOT(slotCurrentPic(QModelIndex)));
model->select();
}
void MainWindow::on_screenButton_clicked()
{
QFileDialog dialog(this);
dialog.setNameFilter(tr("*.png *.gif *.jpg *.tif *.xpm"));
dialog.setFileMode(QFileDialog::ExistingFiles);
dialog.setViewMode(QFileDialog::Detail);
//QPixmap inPixmap =QFileDialog::getOpenFileName(this,tr("Open Image"),"../AIC_Incoming_Images",tr ("Image Files(*.png *.gif *.jpg *.tif *.xpm)"));
//QStringList inPixmap =QFileDialog::getOpenFileNames(this,tr("Open Image"),"../AIC_Incoming_Images",tr ("Image Files(*.png *.gif *.jpg *.tif *.xpm)"));
QString filename_1 =QFileDialog::getOpenFileName(this,tr("Open Image"),"../AIC_Incoming_Images",tr ("Image Files(*.png *.gif *.jpg *.tif *.xpm)"));
QString filePath = QFileInfo(filename_1).fileName();
QImage image_1(filename_1);
QPixmap inPixmap =QPixmap::fromImage(image_1);
//QPixmap inPixmap = screen->grabWindow( 0 ); // Keeping it in the image of the object QPixmap
QByteArray inByteArray; // Create QByteArray object to save the image
QBuffer inBuffer( &inByteArray ); // Saving images produced through the buffer
inBuffer.open( QIODevice::WriteOnly ); // Open buffer
inPixmap.save( &inBuffer, "PNG" ); // Write inPixmap in inByteArray
// Write a screenshot of the database
//db->insertIntoTable(QDateTime::currentDateTime().toString("dd.MM.yyyy_hh:mm:ss.png"), inByteArray);
db->insertIntoTable(filePath, inByteArray);
model->select();
}
void MainWindow::slotCurrentPic(QModelIndex index)
{
QPixmap outPixmap = QPixmap(); // Create QPixmap, which will be placed in picLabel
/* Taking the image data from the table as QByteArray and put them in QPixmap
* */
outPixmap.loadFromData(model->data(model->index(index.row(), 2)).toByteArray());
ui->picLabel->setPixmap(outPixmap.scaled(1000,450));
m_selectedId = model->data(model->index(index.row(), 0)).toInt();
}
void MainWindow::on_Delete_Button_clicked(QModelIndex index)
{
db->removeRecord(id);
}