erbal
erbal

Reputation: 727

Connect to a SLOT in Qt

I have a main window, where is a button, which creates a new window, if pressed. So it works fine, my problem is that I have an another button on the second window. I would like to connect it to a slot, but I always got an error

No such slot dbManager::addQuestions(QString(question->text()))

This is where I want to connect

void WindowManager::addQuestionDialog(){
...
    question = new QLineEdit();
    QObject::connect(validBtn,SIGNAL(clicked()), &db, SLOT(addQuestions(QString(question->text()))));
...
}

And this is where I want to conenct (cpp):

bool dbManager::addQuestions(QString& a){
    qDebug()<<"Connection";
    return true ;
}

.h public slots:

   bool addQuestions(QString& a);

Upvotes: 1

Views: 221

Answers (3)

Nikos C.
Nikos C.

Reputation: 51890

The problem is the way you're trying to connect:

QObject::connect(validBtn,SIGNAL(clicked()), &db,
                 SLOT(addQuestions(QString(question->text()))));

QObject::connect() tries to set up a connection, it doesn't actually pass any arguments. So:

SLOT(addQuestions(QString(question->text())))

is ill formed because you're trying to pass question->text() as an argument. You can't do that. If you want the slot to receive an argument, it's the signal that should pass it. So you need a signal with a QString argument.

There's multiple ways to solve this. The easiest would be to create a new slot which doesn't take any arguments and which calls addQuestions(). For example:

void WindowManager::onValidBtnClick()
{
    question = new QLineEdit();
    db.addQuestions(question->text()));
}

And you connect to that:

void WindowManager::addQuestionDialog()
{
    // ...
    connect(validBtn, SIGNAL(clicked()), SLOT(onValidBtnClick()));
    // ...
}

Upvotes: 3

Barış Akkurt
Barış Akkurt

Reputation: 2256

A signal's signature and the slot's signature must be matched to connect them properly. A useful blog entry for debugging signals and slots: http://samdutton.wordpress.com/2008/10/03/debugging-signals-and-slots-in-qt/

From the documentation:

 The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.) Since the signatures are compatible, the compiler can help us detect type mismatches. 

Also please use the new connection syntax. That way you can catch some mistakes at compile time.

Upvotes: 0

David Elliman
David Elliman

Reputation: 1399

I believe a slot should always return void. Also do you have the Q_OBJECT macro in your class with the slot and is it public. Like this:

class Counter : public QObject
{
    Q_OBJECT
    int m_value;
public:
    int value() const { return m_value; }
public slots:
    void setValue(int value);

Upvotes: 0

Related Questions