0

有没有办法将静态方法的参数传递给类方法?
我用这种方式尝试过 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 构造函数中实例化它

有什么建议吗?谢谢

4

1 回答 1

3

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

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

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

于 2021-10-04T11:13:50.497 回答