【问题标题】:QT C++ - Using MainWindow class QString in a thread classQT C++ - 在线程类中使用 MainWindow 类 QString
【发布时间】:2017-02-13 17:46:35
【问题描述】:

我正在尝试学习线程,以及 C++ 和 QT 的基础知识。我有一个 mainWindow 按钮方法,它本质上将运行一个线程,并存储 ui 组合框文本的值:

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;
  }
}

在线程调用中,当它运行时,我想使用 MainWindow 中的数据成员,特别是 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);
    }
}

在我的 mainwindow.h 中

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();
  test_thread *mThread;
  QString curr_request = "";

我的线程包括 mainwindow.h 文件。 我收到错误:非静态数据成员“curr_request”的使用无效。

【问题讨论】:

  • 这与 C 有什么关系?不要垃圾标签!
  • 我正在尝试学习线程 - this article 是一个很好的起点。

标签: c++ multithreading qt


【解决方案1】:

由于curr_request 是你的类MainWindow 的成员,你必须通过MainWindow 的对象来访问它,例如

MainWindow mainWindow;
mainWindow.curr_request = "something";

或者做这样的事情:

MainWindow* pMainWindow = QCoreApplication::instance()->findChild<MainWindow>();
QString temp = pMainWindow->curr_request;

请注意,这可能不是线程安全的,并且可能会或可能不会导致竞争条件,具体取决于您访问实例的方式。

(来源:here 提出了一个有点类似的问题,其中评论了这种可能性)。

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多