スレッドはメインウィンドウにイベント(メッセージ)を送信し、文字列を渡します.
#ifndef CUSTOMEVENT_H
#define CUSTOMEVENT_H
#include
#include
class CustomEvent : public QEvent //
{
public:
CustomEvent(const QString & msg);
static QEvent::Type m_eventType; //
static QEvent::Type evType(); //
QString m_msg; //
};
#endif // CUSTOMEVENT_H
#include "CustomEvent.h"
QEvent::Type CustomEvent::m_eventType = (QEvent::Type)QEvent::registerEventType(); //
CustomEvent::CustomEvent(const QString &msg)
:QEvent(evType()), m_msg(msg)
{}
QEvent::Type CustomEvent::evType()
{
return m_eventType;
}
#include "widget.h"
#include
#include
#include
#include
#include
//
class SimpleThread: public QThread
{
public:
SimpleThread(QObject *receiver)
: m_receiver(receiver)
{}
void run()
{
while(1)
{
QThread::msleep(1000);
CustomEvent *ce = new CustomEvent(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
QCoreApplication::postEvent(m_receiver, ce); // ,
}
}
QObject *m_receiver; //
};
// :
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_label = new QLabel(this); //
SimpleThread *t = new SimpleThread(this); //
t->start(); // ,
}
Widget::~Widget()
{
}
bool Widget::event(QEvent *e) //
{
if(e->type() == CustomEvent::evType()) // ,
{
CustomEvent *ce = (CustomEvent*)e;
m_label->setText(ce->m_msg); // m_label
m_label->adjustSize();
e->accept(); // ,
return true;
}
return QWidget::event(e); // ,
}
参照先:
https://www.yuque.com/docs/share/0ccc1671-fe98-4122-8ebf-7fc0ef7132f8