I'm trying to learn about threading, and the basics of C++ and QT. I have a mainWindow button method that will essentially run a thread, and store the value of a ui combobox text:
void MainWindow::on_Request_Raw_Button_clicked(bool checked)
{
if(checked)
{
// Store the current request into var.
curr_request = ui->comboBox_2->currentText();
qDebug() << curr_request << " started.\n";
mThread->start();
}
else
{
qDebug() << "Stopped.\n";
mThread->Stop = true;
}
}
And in the thread call, when it runs I want to use the data member in MainWindow , specifically curr_request.
test_thread::test_thread(QObject *parent) : QThread(parent)
{
}
void test_thread::run()
{
this->Stop = false;
QMutex mutex;
while(true)
{
qDebug() << "I started.\n";
if( this->Stop ) {
break;
mutex.unlock();
}
/* Do stuff here */
qDebug() << "Test: " << curr_request;
QString temp = curr_request;
mutex.unlock();
emit temp;
this->usleep(900000);
}
}
In my mainwindow.h
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
test_thread *mThread;
QString curr_request = "";
My thread includes the mainwindow.h file. I get the error: Invalid use of non-static data member 'curr_request'.
Since curr_request
is a member of your class MainWindow
, you have to access it through an object of MainWindow
, eg
MainWindow mainWindow;
mainWindow.curr_request = "something";
Or do something like this:
MainWindow* pMainWindow = QCoreApplication::instance()->findChild<MainWindow>();
QString temp = pMainWindow->curr_request;
Beware that this is possibly not thread-safe and may or may not lead to a race condition, depending on how you access the instance.
(Source: A somewhat similar question was has been asked here , where this possibility was commented).
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.