通常、カスタム イベントを使用するには、独自の QEvent サブクラスを作成し、イベントを受け取る QObject クラス (多くの場合メイン ウィンドウ クラス) で customEvent() をオーバーライドし、スレッドからレシーバーにイベントを「ポスト」するコードを使用します。
イベント投稿コードをレシーバー クラスのメソッドとして実装するのが好きです。そうすれば、呼び出し元は受信者オブジェクトについて知るだけでよく、「Qt」の詳細はわかりません。呼び出し元は、このメソッドを呼び出します。このメソッドは、本質的にメッセージを自分自身にポストします。うまくいけば、以下のコードがより明確になります。
// MainWindow.h
...
// Define your custom event identifier
const QEvent::Type MY_CUSTOM_EVENT = static_cast<QEvent::Type>(QEvent::User + 1);
// Define your custom event subclass
class MyCustomEvent : public QEvent
{
public:
MyCustomEvent(const int customData1, const int customData2):
QEvent(MY_CUSTOM_EVENT),
m_customData1(customData1),
m_customData2(customData2)
{
}
int getCustomData1() const
{
return m_customData1;
}
int getCustomData2() const
{
return m_customData2;
}
private:
int m_customData1;
int m_customData2;
};
public:
void postMyCustomEvent(const int customData1, const int customData2);
....
protected:
void customEvent(QEvent *event); // This overrides QObject::customEvent()
...
private:
void handleMyCustomEvent(const MyCustomEvent *event);
customData1とはcustomData2、イベントでデータを渡す方法を示すためにあります。sである必要はありませんint。
// MainWindow.cpp
...
void MainWindow::postMyCustomEvent(const int customData1, const int customData2)
{
// This method (postMyCustomEvent) can be called from any thread
QApplication::postEvent(this, new MyCustomEvent(customData1, customData2));
}
void MainWindow::customEvent(QEvent * event)
{
// When we get here, we've crossed the thread boundary and are now
// executing in the Qt object's thread
if(event->type() == MY_CUSTOM_EVENT)
{
handleMyCustomEvent(static_cast<MyCustomEvent *>(event));
}
// use more else ifs to handle other custom events
}
void MainWindow::handleMyCustomEvent(const MyCustomEvent *event)
{
// Now you can safely do something with your Qt objects.
// Access your custom data using event->getCustomData1() etc.
}
何も置き忘れていないことを願っています。これが整ったら、他のスレッドのコードは、オブジェクトへのポインターを取得してMainWindow(それを と呼びましょうmainWindow)、呼び出すだけです。
mainWindow->postMyCustomEvent(1,2);
ここで、例として、1and2は任意の整数データにすることができます。