2012-07-19 33 views
0

我試圖連接一個組合框值和一個標籤,這樣當組合框更改標籤時反映了這一點。我一直在努力尋找答案,但是,至今爲止,沒有任何工作能夠奏效;我仍然得到的錯誤:no matching function for call to mainWindow::connect(QComboBox*&, const char [38], QString*, const char [26])Qt沒有調用mainWindow :: connect()的匹配函數

我試過QObject::connect,QWidget::connect和其他任何與Qt處理,但無濟於事。

創建一個說明組合框值的標籤並不是我對程序的最終意圖。相反,我希望得到它與一個簡單的標籤工作,然後將其更改爲我想要它顯示(因此tempLabel)。

mainwindow.h:

class MainWindow : public QMainWindow 
{ 
public: 
    MainWindow(); 

private slots: 
    QString getClass(QComboBox *box); 
}; 

mainwindow.cpp:

MainWindow::MainWindow() 
{ 
    QString qMathClassName; 

    QComboBox* mathClassCombo = new QComboBox; 
    QLabel* label = new QLabel(qMathClassName); 

    // omitting layout code... 

    connect(mathClassCombo, SIGNAL(currentIndexChanged(const QString &)), 
      &qMathClassName, SLOT(getClass(mathClassCombo))); 
} 

QString MainWindow::getClass(QComboBox *box) 
{ 
    return box->currentText(); 
} 

任何幫助將不勝感激!

+0

你混淆類,實例和值。這三件事不可互換。 QmathClassName是一個實例。它的類型是QString。它的值與「」類似。 – cgmb 2012-07-20 20:12:55

回答

1

您正在將信號連接到具有不同簽名的插槽。你必須改變你的插槽像

getClass(const QString &) 

匹配currentIndexChanged信號。

+0

謝謝!有它編譯,但現在到一個新的問題! – synthrom 2012-07-20 16:30:12

2

我想你需要閱讀Qt的signals and slots documentation。再次,如果你已經這樣做了。要特別注意他們的例子。

我認爲你在C++中有關於Qt這些誤解:

  1. 這QLabel需要爲QString的引用,它會更新其在文本字符串的變化。它不會。當你給它字符串時,QLabel將顯示字符串的值。這是唯一一次更新。

  2. 構建在堆棧上的對象在函數結束時不會被銷燬。他們不會。在構造函數的最後,qMathClassName將被銷燬,任何對它的引用都將失效。因此,即使可以,您也不想與之建立聯繫。

  3. QObject :: connect的第三個參數是指向放置插槽返回值的位置的指針。不是。第三個參數是一個指向調用該插槽的QObject的指針。對於通過QObject :: connect進行的任何調用,插槽的返回值都是未使用的。

  4. 您可以將值綁定到連接中的插槽。不幸的是,在SLOT宏中,您必須放置插槽的功能簽名。你不可以引用任何變量。參數部分必須只有類名。那是SLOT(getClass(QComboBox*)),而不是SLOT(getClass(mathClassCombo))

顯示在標籤,以確保組合框的內容,最簡單的方法是這樣的:

QComboBox* mathClassCombo = new QComboBox; 
QLabel* tempLabel = new QLabel; 
connect(mathClassCombo, SIGNAL(currentIndexChanged(const QString&)), 
     tempLabel, SLOT(setText(const QString&))); 

如果你想要做一些更復雜,我建議只是讓一個插槽上的可以處理這些複雜問題的窗口。例如:

mainwindow.h:

class MainWindow : public QMainWindow 
{ 
Q_OBJECT 
public: 
    MainWindow(); 

private slots: 
    void updateLabelText(const QString& className); 

private: 
    QComboBox* mathClassCombo; 
    QLabel* tempLabel; 
} 

mainwindow.cpp:

MainWindow::MainWindow() 
{ 
    mathClassCombo = new QComboBox; 
    tempLabel = new QLabel; 

    // omitting layout code... 

    connect(mathClassCombo, SIGNAL(currentIndexChanged(const QString&)), 
      this, SLOT(updateLabelText(const QString&))); 
} 

void MainWindow::updateLabelText(const QString& className) 
{ 
    QString newLabelString = className + " is the best class ever!"; 
    tempLabel->setCurrentText(newLabelString); 
}