I have a class that inherits QThread designed to use a QTcpSocket to receive data from some server:
class ReceiveThread
: public QThread{
Q_OBJECT
public:
virtual ~ReceiveThread();
protected:
void run();
private:
int _port;
QTimer * _connectionAttemptTimer;
};
void ReceiveThread::run()
{
_connectionAttemptTimer->start(); // problem 1
_socket->connectToHost( _address, _port ); // problem 2
exec();
}
class ReceiveThread : public QThread
{
Q_OBJECT
public:
ReceiveThread( QHostAddress address, int port, QWidget * parent = 0 );
virtual ~ReceiveThread();
protected:
void run();
private:
QAbstractSocket * _socket;
QHostAddress _address;
int _port;
QTimer * _connectionAttemptTimer;
};
void ReceiveThread::run()
{
_connectionAttemptTimer->start(); // problem 1
_socket->connectToHost( _address, _port ); // problem 2
exec();
}
To copy to clipboard, switch view to plain text mode
I also have a QWidget in which I want to use this class:
ConfigWidget
::ConfigWidget( QWidget* parent
) : QWidget( parent
), _ui
(new Ui_ConfigWidget
()){
_ui->setupUi( this );
_receiveThread = new ReceiveThread(
connect( _ui->testConnectionPushButton, SIGNAL( clicked() ),
this, SLOT( testConnectionPushButtonClicked() ) );
}
void ConfigWidget::testConnectionPushButtonClicked()
{
_receiveThread->start();
}
ConfigWidget::ConfigWidget( QWidget* parent ) : QWidget( parent ), _ui (new Ui_ConfigWidget())
{
_ui->setupUi( this );
_receiveThread = new ReceiveThread(
QHostAddress( "192.168.1.2" ), 9000 );
connect( _ui->testConnectionPushButton, SIGNAL( clicked() ),
this, SLOT( testConnectionPushButtonClicked() ) );
}
void ConfigWidget::testConnectionPushButtonClicked()
{
_receiveThread->start();
}
To copy to clipboard, switch view to plain text mode
I basically get 2 errors when it executes the run() method of the QThread (marked above in the code):
QObject::startTimer: timers cannot be started from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTcpSocket(0x2255780), parent's thread is QThread(0x2160250), current thread is ReceiveThread(0x224fe90)
I kind of understand... but not really...
Bookmarks