0

We're trying to write a simple messenger, and have encountered with a problem. Our program crashes when we are calling repaint from another thread. Here is a part of our code

`

//client.cpp
#include "main_window.h"
extern main_window * m_parent; //m_parent in main_window constructor get assigned with this
std::list<std::string> m_online_contacts;

void client::contacts(std::string str)
{
    m_online_contacts.clear();
    std::string user_n = "";
    size_t j = 0;
    size_t size = str.size();
    j = str.find(':');
    if (size > 2){
        str = str.substr(j + 1);
        j = str.find(':');
        while(j != std::string::npos){
            user_n = str.substr(0, j);
            m_online_contacts.push_back(user_n);
            str = str.substr(j + 1);
            j = str.find(':');
        }
        m_online_contacts.push_back(str);
    }
   if(m_parent)
        m_parent->create_contacts(m_online_contacts);
}



//main_window.cpp

void main_window::create_contacts(std::list< std::string> l)
{
    for(int j = 0; j < m_count; ++j){ //m_count is a count of on-line users
        if(m_users[j]) { //m_users[] is a list of users to be shown
            delete m_users[j];
        }
    }
    if(m_users) {
        delete [] m_users;   
    } 
    m_count = 0;
    std::list <std::string> :: iterator it = l.begin();
    if(l.size() == 0) {
        m_users = new m_label* [1];
        m_users[0] = new m_label(QString::fromStdString("No online contacts"));
    m_layout->addWidget(m_users[0]);
        m_count = 1;
    }
    else {
        m_users = new m_label * [l.size()];
        for (int i = 0; it != l.end(); ++it) {
            m_users[i] = new m_label (QString::fromStdString(*it));
            m_layout->addWidget(m_users[i++]);
            ++m_count;
        }
    }
    this->repaint();
}

` client.cpp and main_window.cpp are different files and work in different threads

and here is a crash message

QObject::setParent: Cannot set parent, new parent is in a different thread
QObject::setParent: Cannot set parent, new parent is in a different thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
Segmentation fault
cinemarter
  • 61
  • 1
  • 6

1 Answers1

0

I am not a qt expert, but it looks like qt doesn't want you to mess with windowing things (repainting) outside of the GUI thread. This seems reasonable to me, because otherwise there would have to be a ton of locks in the windowing code to make it work safely. Shouldn't the main GUI thread be repainting on its own anyways?

Craig H
  • 7,949
  • 16
  • 49
  • 61
  • We need the window to be repainted when client::contacts is called. How shall we do that than? – cinemarter Jan 27 '12 at 19:00
  • SO contains a lot of questions about threads and qt. For example, this question from yesterday has an answer for you too: http://stackoverflow.com/questions/9018434/qthread-doesnt-work-well –  Jan 27 '12 at 19:39