QSocketNotifier:只能与以 QThread 错误开头的线程一起使用

QSocketNotifier: Can only be used with threads started with QThread error

本文关键字:开头 线程 一起 错误 QThread QSocketNotifier      更新时间:2023-10-16

我正在尝试使用QLocalServer作为IPC解决方案。qt 的版本是 4.6

这是我的主要.cpp:

int main(int argc, const char*argv[]) {  
  QServer test();
  while (true) {
  }
}

这是我的QServer课程:

class QServer : public QObject
{
 Q_OBJECT
public :
 QServer ();
  virtual ~QServer();
private :  
  QLocalServer* m_server;
  QLocalSocket* m_connection;

private slots:
  void socket_new_connection();
};
QServer::QServer()
{
  m_server = new QLocalServer(this);
  if (!m_server->listen("DLSERVER")) {
    qDebug() << "Testing";
    qDebug() << "Not able to start the server";
    qDebug() << m_server->errorString();
    qDebug() << "Server is " << m_server->isListening();
  }
  connect(m_server, SIGNAL(newConnection()),
          this, SLOT(socket_new_connection()));
}
void
QServer::socket_new_connection()
{
  m_connection = m_server->nextPendingConnection();
  connect(clientConnection, SIGNAL(readyRead()),
          this, SLOT(newData(clientConnection)));
}

这一切都可以编译,但是在运行时,当我尝试连接newConnection()时,我得到一个QSocketNotifier:只能与以QThread错误开头的线程一起使用。

我尝试将整个东西包装在 QThread 中,但我仍然收到同样的错误。

谁能解释一下我做错了什么,或者为什么甚至涉及一个线程?

错误消息具有误导性。你需要一个Qt事件循环才能使用QSocketNotifier。在您的应用程序中执行此操作的适当方法是创建一个 QApplication(或者如果您不需要任何图形内容,则创建 QCoreApplication)。您的主要内容应如下所示:

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
    QServer test();
    app.exec();
    return 0;
}

QCoreApplication::exec() 启动事件循环(替换while (true) {}循环)。