2011-03-23 25 views
0

我希望通過朋友函數在ListWidget(它是一個類的私有成員)中添加項目。實際上,我正在嘗試使用這個示例代碼片段來使用更多類的朋友函數來從單個函數更新其ListWidgets。在QT中使用Friend函數的問題

我需要指導在我的情況下使用朋友功能。

請原諒我對這個話題的無知,任何幫助表示讚賞。

class InBoxTab : public QWidget 
    { 
    Q_OBJECT 

    public: 
     InBoxTab(QWidget *parent = 0); 
     // InBoxTab(); 
     ~InBoxTab(); 

    public slots: 
     void hello(); 
     friend void adda(); // friend function 
    private: 
     QListWidget* listWidget1; //data member accessed by friend function 
    }; 



    void adda() 
    { 
     InBoxTab I; 

     I.listWidget1->insertItem(1,QString("added frm fn")); 

     I.listWidget1->update(); 
    } 


InBoxTab::InBoxTab(QWidget *parent) : 
     QWidget(parent) 
{ 
     listWidget1 = new QListWidget(this); 

     QListWidgetItem* item = new QListWidgetItem("Item 1 added frm tab1 "); 

     listWidget1->addItem(item); 
     adda(); // Call to friend function 

     QVBoxLayout* layout = new QVBoxLayout(this); 
     layout->addWidget(listWidget1); 
     this->setLayout(layout); 
} 
+0

什麼是錯誤信息? – Mahesh 2011-03-23 21:35:40

+0

那麼你的問題是什麼? – TonyK 2011-03-23 21:35:42

+0

我沒有收到任何錯誤消息。沒有構建問題。但是,我的私人數據成員也沒有被朋友功能更新,這本身就是問題所在。 – dipeshtech 2011-03-23 22:18:49

回答

0

據我所看到的, 'ADDA' 功能不會造成任何影響。它不返回任何內容,只在'add'結束時刪除'I'。

的如何,我相信你可以用朋友的功能是,如果你申報/定義的「阿達」爲例:

void adda(InBoxTab *I) 
{ 
     I->listWidget1->insertItem(1,QString("added frm fn")); 
     I->listWidget1->update(); 
} 

......雖然在特定情況下,沒有理由不使'adda'代替InBoxTab的成員。

+0

謝謝!我得到了我正在尋找的東西。 – dipeshtech 2011-03-25 20:07:42

0
void adda() 
{ 
    InBoxTab I; 

    I.listWidget1->insertItem(1,QString("added frm fn")); 

    I.listWidget1->update(); 
} 

InBoxTab::InBoxTab(QWidget *parent) : 
      QWidget(parent) 
{ 
    // ... 

    adda(); // Call to friend function 

    // .. 
} 

在功能adda(),一個新的對象調用時創建I。所以,構造函數被調用,構造函數inturn再次調用adda(),並且過程繼續。我看到一個無限遞歸這是問題所在。


編輯:

InBoxTab(QWidget *parent = 0); // Since parent is initialized to 0 if nothing 
           // is passed to constructor up instantiation 

InBoxTab I; // Invokes the above constructor and an infinite recursion results. 
+0

是啊.. !!對..!!我試過把它放進另一個插槽,但那也不會更新列表。 – dipeshtech 2011-03-23 21:50:34

+0

@ dipeshtech-我不知道'QT',而是一個問題。你爲什麼想要在設計中擁有「朋友」功能? – Mahesh 2011-03-23 21:56:09

+0

我在考慮使用Friend函數,因爲我想更新(添加/刪除)2個類的listwidget(私有成員)中的項目,我想這是爲了在我的項目中實現一個功能。我也嘗試過朋友類,並且我沒有收到任何錯誤,但沒有列表也被更新。我正在使用諾基亞QT SDK – dipeshtech 2011-03-23 22:13:50