我有一个使用QDBus
连接到蓝牙打印机的应用程序。配对打印机后,我调用Connect
接口org.bluez.Serial
。我意识到这实际上冻结了 UI,直到调用返回。我创建了一个工作对象,然后移到了一个单独的对象QThread
,也没有解决问题。
Worker* w = new Worker();
QThread* thread = new QThread();
w->moveToThread(thread);
connect(thread, &QThread::started, w, &BluetoothPrinter::Worker::print);
connect(w, &BluetoothPrinter::Worker::finished, thread, &QThread::quit);
connect(w, &BluetoothPrinter::Worker::finished, w, &BluetoothPrinter::Worker::deleteLater);
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
connect(w, &BluetoothPrinter::Worker::destroyed, []() { qDebug() << "worker destroyed"; });
connect(thread, &QThread::destroyed, []() { qDebug() << "thread destroyed"; });
thread->start();
这就是我调用函数Connect
的方式。BluetoothPrinter::Worker::print
QDBusInterface dbusSerialInterface("org.bluez", objPath, "org.bluez.Serial", QDBusConnection::systemBus(), this);
if (dbusSerialInterface.isValid()) {
QDBusMessage reply = dbusSerialInterface.call("Connect", "spp"); // freezes UI here
if (reply.type() == QDBusMessage::ErrorMessage || reply.arguments().isEmpty()) {
emit finished();
return;
}
...........
}
谢谢。