2

I have set a main window QP_Qt with a label on it named serverStatusLabel:

class NP_Qt : public QMainWindow
{
    Q_OBJECT

public:
    NP_Qt(QWidget *parent = 0, Qt::WFlags flags = 0);
    ~NP_Qt();
    void setServerStatusLabel(QString status);
    void setClientStatusLabel(QString status);

private:
    Ui::NP_QtClass ui;
}

void NP_Qt::setServerStatusLabel(QString status)
{
    ui.TCPServerStatusLabel->setText(status);
}

No error occurred during compilation. At runtime, When setServerStatusLabel is called from another class:

void ServerListenThread::run()
{
    if(! tcpServer.listen(QHostAddress::LocalHost, portNumber)) {
        window->setServerStatusLabel("Failed to listen on this port");
    } else {
        window->setServerStatusLabel("Listening");
    }
}

Error occurred:

Unhandled exception at 0x771115de of SP_Qt.exe: 0xC0000005 : access violation at 0xccccce2c  

What may cause this error ?

CDT
  • 10,165
  • 18
  • 66
  • 97

1 Answers1

3

Are you sure you don't access pointer in setServerStatusLabel(QString status): ui.TCPServerStatusLabel? Try changing it to ui->TCPServerStatusLabel.

Edit:

I would also recommend you to use Qt Signal/Slot system instead of calling functions from other thread directly. Something like this:

In your thread's header file write signal definition:

signals:
    void changeStatus(QString newStatus);

In NP_Qt window, write slot definition in header:

public slots:
    void statusChanged(QString newStatus);

And connection in CPP file:

connect (myThread, SIGNAL(changeStatus(QString)),
         this, SLOT(statusChanged(QString)));

Finally, emit signal in your thread:

emit changeStatus("Hello from thread!");
ahawkthomas
  • 656
  • 3
  • 13
  • 26
  • It works fine ! I'm new to Qt so I'm not familiar with Signal/Slot system. Would you please tell me why Signal/Slot system is preferred to just calling functions directly ? – CDT May 27 '13 at 01:40
  • Well, I would recommend you to read [this](http://qt-project.org/doc/qt-4.8/signalsandslots.html) article: it explains a lot. In short: you cannot achieve connection between separate threads without special thread-safe mechanism. Qt Signals/Slots represent this mechanism. You may also use [`QMetaObject::invokeMethod`](http://stackoverflow.com/questions/1144240/qt-how-to-call-slot-from-custom-c-code-running-in-a-different-thread), but it is harder. – ahawkthomas May 27 '13 at 01:52
  • 1
    Please check the docs provided with Qt. There is a lot of info and a complete tutorial. Without it you'll do more errors like this in future. – Kamil Klimek May 27 '13 at 08:26