#ifndef STORE_H#define STORE_H#include <QtGui/QDialog>#include "ui_store.h"class QThread;class threadobj;class store : public QDialog{ Q_OBJECTpublic: store(QWidget *parent = 0, Qt::WFlags flags = 0); ~store();private: Ui::storeClass ui; QThread *m_thread; threadobj *m_obj;};#include "store.h"#include "threadobj.h"#include <QSqlDatabase>#include <QThread>store::store(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags){ ui.setupUi(this); QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("test.sqlite"); db.open(); m_thread = new QThread; m_obj = new threadobj; m_obj->moveToThread(m_thread); connect(m_thread, SIGNAL(started()), m_obj, SLOT(checkTable())); connect(m_obj, SIGNAL(finished()), m_thread, SLOT(quit())); m_thread->start();}store::~store(){ if (m_thread->isRunning()) { m_thread->quit(); m_thread->wait(); } QSqlDatabase db = QSqlDatabase::database(); db.close();}#endif // STORE_H
#ifndef THREADOBJ_H#define THREADOBJ_H#include <QObject>class threadobj : public QObject{ Q_OBJECTpublic: threadobj(QObject *parent = 0); ~threadobj();public slots: void checkTable();signals: void finished();};#endif // THREADOBJ_H#include "threadobj.h"#include <QSqlQuery>#include <QSqlError>#include <QVariant>#include <QDebug>threadobj::threadobj(QObject *parent) : QObject(parent){}threadobj::~threadobj(){}void threadobj::checkTable(){ QSqlQuery q; if (!q.exec("select count(id) from orders")) { qDebug() << q.lastError().text(); } else { q.first(); int c = q.value(0).toInt(); qDebug() << c; } emit finished();}
C++ (Qt)qDebug() << QThread::currentThreadId();