Alex
Alex

Reputation: 36151

Qt: why does connect() work only in the main window class?

Here's a simple code that creates a button and assigns a onclick handler:

auto btn = new QPushButton("CLICK ME");
connect(btn, SIGNAL(clicked()), this, SLOT(btn_Click()));

private slots:
void btn_Click() {
    alert("clicked!");
}

It works as it should if called in the main window class. However when I try to do this in a child window, clicking the button does nothing. The child window is shown like this:

auto settingsWindow = new SettingsWindow();
settingsWindow->show();

I guess it's somehow connected with the receiver object which is now a different window. But how can I make it work?

Upvotes: 0

Views: 397

Answers (2)

wuliang
wuliang

Reputation: 749

You should add a MACRO in class SettingsWindow to enable singal receiving. Add "Q_OBJECT" like the following.

class MainWidget : public QWidget
{
    Q_OBJECT
    public:
    MainWidget();
....

Upvotes: 2

Artak Begnazaryan
Artak Begnazaryan

Reputation: 469

In order to be able to declare signals/slots in your own class you should include Q_OBJECT directive in your class:

class SettingsWindow {
        Q_OBJECT

        ...
};

Upvotes: 5

Related Questions