我将数据库连接用作全局记录器,因此您可以对其进行调整以满足您的需求。骨架看起来像:
//Logger.h
class Logger : public QObject
{
Q_OBJECT
...
public:
void log(const QString& msg):
private:
LoggerWorker* w;
QThread t;
}
// Logger.cpp
Logger::Logger(QObject* p)
:QObject(p)
{
w = new LoggerWorker;
w->moveToThread(&t);
connect(&t, SIGNAL(started()), w, SLOT(init()));
t.start();
}
...
void
Logger::log(const QString& msg)
{
QMetaObject::invokeMethod(w, "log", Q_ARG(QString, msg));
}
// LoggerWorker.h
class LoggerWorker : public QObject
{
Q_OBJECT
...
public slots:
void init()
{
// create database and connect to it
}
void log(const QString& msg)
{
// insert to database
}
private:
QSqlDatabase db;
}
注意:上面的代码可能包含坚果和错误
干杯