Main(函数main在那里)我的程序的线程保留用于非GUI任务.它调用了许多冗长的计算功能.所有已实现的GUI都在一个单独的线程中完成它们的工作.
我现在要使用Qt实现一个GUI.Qt文档说所有GUI相关的任务都应该在主线程中完成.在我的例子中,在主线程中偶尔插入QCoreApplication :: processEvents()调用几乎没用,因为它们之间有很大的延迟.
有没有办法克服Qt的这种约束?是不可能在Qt程序的主线程中做一些非GUI相关的事情?
我有一个从两个QThreads主线程调用的方法.这个方法有时需要花费很长时间才能在循环中进行计算,所以我放了QCoreApplication::processEvents()这个就可以防止GUI冻结.在某些时候我已经改变QCoreApplication::processEvents()了QApplication::processEvents()但是这导致GUI冻结(我非常确定那是什么令人惊叹它因为我QCoreApplication::processEvents()放回它还没有再次冻结)我是正确的认为QApplication::processEvents()从主线程和QThreads调用可以冻结GUI?
我实现了一个类,它可以通过QQueue将数据写入串口,并通过插槽读取.我使用QAsyncSerial来反过来使用boost :: asio和回调.该类被移动到一个线程,当QThread发出"started()"时,它的start()方法被执行
问题是我使用forever {}和QWaitCondition在start() - 方法中使QQueue出列.当这个运行时(显然会永远运行),连接到QAsyncSerial的dataReceived信号的插槽无法被调用,因此我从未从串口读取任何内容.
解决这个问题的常用方法是什么?
SerialPortHandler::SerialPortHandler(SerialPort serialPort, QObject *parent) : QObject(parent), serialPort(serialPort)
{
m_enqueueMessageMutex = new QMutex();
m_messageQueue = new QQueue<BaseMessage*>();
m_waitCondition = new QWaitCondition();
serial.open(serialPort.deviceName(), 2400);
connect(&serial, SIGNAL(dataReceived(QByteArray)), this, SLOT(serialSlotReceivedData(QByteArray)));
}
void SerialPortHandler::serialSlotReceivedData(QByteArray line)
{
qDebug() << QString(line).toAscii();
}
void SerialPortHandler::sendTestPing()
{
PingMessage *msg = new PingMessage();
enqueueMessage(msg);
}
void SerialPortHandler::enqueueMessage(BaseMessage *msg)
{
QMutexLocker locker(m_enqueueMessageMutex);
m_messageQueue->enqueue(msg);
m_waitCondition->wakeAll();
}
void SerialPortHandler::start()
{
if (!serial.isOpen())
return;
forever {
m_enqueueMessageMutex->lock();
if (m_messageQueue->isEmpty())
m_waitCondition->wait(m_enqueueMessageMutex);
BaseMessage *msg = m_messageQueue->dequeue();
serial.write(msg->encodeForWriting());
m_enqueueMessageMutex->unlock(); …Run Code Online (Sandbox Code Playgroud)