Qt/C++ 将静态方法的参数传递给 class 方法

Qt/C++ pass static method's argument to class method

有没有办法将静态方法的参数传递给 class 方法?
我以这种方式尝试过 QTimer:

QTimer g_timer;
QString g_arg;

void staticMethod(QString arg)
{
  g_arg = arg;
  g_timer.start(1); // It will expire after 1 millisecond and call timeout()
}

MyClass::MyClass()
{
  connect(&g_timer, &QTimer::timeout, this, &MyClass::onTimerTimeout);

  this->moveToThread(&m_thread);
  m_thread.start();
}

MyClass::onTimerTimeout()
{
  emit argChanged(g_arg);
}

但是我遇到线程错误,因为 staticMethod 是从 Java Activity 调用的,所以线程不是 QThread。

错误是:

QObject::startTimer: QTimer can only be used with threads started with QThread

如果g_timer不是指针,或者

QObject::startTimer: timers cannot be started from another thread

如果 g_timer 是一个指针,我在 MyClass 构造函数中实例化它

有什么建议吗?谢谢

在此特定实例中,您可以使用 QMetaObject::invokeMethod 通过跨线程 QueuedConnection 发送消息:

QMetaObject::invokeMethod(&g_timer, "start", Qt::QueuedConnection, Q_ARG(int, 1));

这会将事件传递到调用 start 方法的拥有线程,而不是当前(非 QT)线程。