2012-01-27 295 views
0

我們正在嘗試編寫一個簡單的使用程序,並且遇到了問題。 當我們從另一個線程調用repaint時,程序崩潰。 這裏是我們的代碼的一部分調用qwidget :: repaint()時發生崩潰

`

//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和main_window.cpp是不同的文件,並在不同的線程

,在這裏工作是一個崩潰的消息

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 
+2

它崩潰,因爲你不能這樣做。在qt.nokia.com上有很好的資料。 – UmNyobe 2012-01-27 15:01:17

+0

這就是當你不閱讀文檔時會發生什麼! – 2012-01-27 15:45:28

回答

0

我不是一個qt專家,但它看起來像qt不希望你在GUI線程以外的窗口事物(重繪)混亂。這對我來說似乎是合理的,因爲否則在窗口代碼中必須有大量的鎖才能使其安全工作。主GUI線程不應該自己刷新?

+0

我們需要在調用client :: contacts時重新繪製窗口。我們該怎麼做呢? – cinemarter 2012-01-27 19:00:35

+0

SO包含很多關於線程和qt的問題。例如,昨天的這個問題也爲你解答:http://stackoverflow.com/questions/9018434/qthread-doesnt-work-well – 2012-01-27 19:39:49