I'm running all my SQLite database operations in a separate thread to ensure that the GUI wont freeze up.
I'm doing this by connecting up signals and slots for the methods.
However now I need to find a way for the SQLite thread to return selected values to my main thread.
My header file:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
// ....
// ....
signals:
QString getUserNickS(QString channel);
}
class dbThread : public QObject
{
Q_OBJECT
public:
dbThread();
public slots:
bool openDB(QString agentID);
QString getUserNick(QString channel);
private:
QSqlDatabase db;
};
I then open the DB connection inside MainWindow
in a separate thread like this:
// Start database thread
QThread * thread = new QThread();
dbtrad = new dbThread();
dbtrad - > moveToThread(thread);
//dbtrad->openDB(agentID);
connect(this, SIGNAL(requestOpenDB(QString)), dbtrad, SLOT(openDB(QString)));
connect(this, SIGNAL(getUserNickS(QString)), dbtrad, SLOT(getUserNick(QString)));
thread - > start();
emit requestOpenDB(userID);
And finally at one point in my application I want to query the SQLite db for some info and receive a return value: (still inside MainWindow
)
QString retVal = getUserNickS(channelId);
qDebug() << "RET VALUE -----> " + retVal;
The getUserNick
method looks like this:
// Returns visitor nickname for a channelId
QString dbThread::getUserNick(QString channel) {
bool ret = false;
if (db.isOpen()) {
QSqlQuery query(db);
ret = query.exec(QString("select * from visitorInfo WHERE channelID = '%1' order by date(time) ASC LIMIT 1;").arg(channel));
if (ret) {
bool gotResults = false;
while (query.next()) {
gotResults = true;
qDebug() << query.value(14).toString();
return query.value(14).toString();
}
if (!gotResults) {
qDebug() << "Name " + channel.replace("V", "");
return "Name " + channel.replace("V", "");
}
} else {
qDebug() << "Name " + channel.replace("V", "");
return "Name " + channel.replace("V", "");
}
}
}
Any ideas how I can get the returned value?
You should have a connection of type Qt::BlockingQueuedConnection when the emitter and receiver are in different threads.
So it should be like:
connect(this, SIGNAL(getUserNickS(QString)), dbtrad, SLOT(getUserNick(QString)),Qt::BlockingQueuedConnection);
When you emit your signal, it causes the current thread to block until the slot is returned.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.