Qt signals and slots for multiple objects

点点圈 提交于 2020-01-03 04:23:16

问题


I'm having little problem here. I'm having troubles with signals & slots. I'll try to explain with pseudocode. So, here it goes.

I have main thread (mainwindow.cpp) where I'm creating new objects when new client connects.

mainwindow.h:

signals:
   void changeText();
...

mainwindow.cpp:

connect(tcpserver, SIGNAL(changeText()), this, SIGNAL(changeText()));

...

MyClass *m = new MyClass(this);
connect(this, SIGNAL(changeText()), m, SLOT(changeText()));

I have also tcpserver class, which creates new QThread when client connects and connects both signals.

tcpserver.h:

signals:
    void changeText();
protected:
    void incomingConnection(int handle);

tcpserver.cpp:

void incomingConnection(int handle)
{
    QTcpSocket *s = new QTcpSocket(this);
    s->setSocketDescriptor(handle);
    mythread *thread = new mythread(s, this);
    connect(thread, SIGNAL(changeText()), this, SIGNAL(changeText()));
}

The problem is following: I have 3 objects, main thread, tcpserver class which inherits from QTcpServer, and the mythread class which inherits from QThread class.

When I'm creating new "mythread"-s from "tcpserver" and connecting signals, all signals from new threads are connected to "tcpserver"-s signals, so, e.g if 10 clients do something, all signals are sent to "tcpserver" which makes problem for me. I want to understand which signal should I connect to MyClass via QTread -> TcpServer -> MainWindow.

Sorry for my English, if you don't understand what I mean, I'll try to explain better.

Thank you.


回答1:


Some suggestions:

  • in your "incomingConnection(int)", i doubt any memory leak for the objects created in heap (tcpsocket, and mythread), use QList (or other container) in your tcpserver to hold the sockets created in your "incomingConnection(int)"
  • prefix the name of SLOT(changeText) with your classes to clarify which objects is your intented sender/receiver
  • I dont think you cant connect two signal like

    connect(thread, SIGNAL(changeText()), this, SIGNAL(changeText()));



来源:https://stackoverflow.com/questions/15316032/qt-signals-and-slots-for-multiple-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!