Qt没有匹配函数来调用mainWindow :: connect()

时间:2012-07-19 23:50:04

标签: c++ qt

我正在尝试连接组合框值和标签,以便在组合框更改时标签反映出来。我搜索了一下我的心脏试图寻找答案但是,到目前为止,没有任何效果;我仍然收到错误:no matching function for call to mainWindow::connect(QComboBox*&, const char [38], QString*, const char [26])

我尝试了QObject::connectQWidget::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();
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

我认为你需要阅读Qt的signals and slots documentation。如果你已经这样做了。特别注意他们的例子。

我认为你在C ++中对Qt有这些误解:

  1. QLabel接受对QString的引用,并在该字符串更改时更新其文本。它不会。当您为字符串提供字符串时,QLabel将显示该字符串的值。这是唯一一次更新。

  2. 在函数结束时不会销毁在堆栈上构造的对象。他们不会。在构造函数的末尾,将销毁qMathClassName,并且对它的任何引用都将变为无效。因此,即使可以,也不想与它建立联系。

  3. QObject :: connect的第三个参数是指向放置槽的返回值的位置的指针。不是。第三个参数是指向要调用插槽的QObject的指针。对于通过QObject :: connect。

  4. 进行的任何调用,槽的返回值都是未使用的
  5. 您可以将值绑定到连接中的插槽。不幸的是。在SLOT宏中,您必须放置插槽的功能签名。您可能不会引用任何变量。参数部分必须只有类名。那是SLOT(getClass(QComboBox*)),而不是SLOT(getClass(mathClassCombo))

  6. 确保组合框内容的最简单方法是在标签中显示:

    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);
    }
    

答案 1 :(得分:1)

您正在将信号连接到具有不同签名的插槽。您必须将广告位更改为

getClass(const QString &)

匹配currentIndexChanged信号。