0

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?

Alex
  • 34,581
  • 26
  • 91
  • 135

2 Answers2

5

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

        ...
};
2

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();
....
wuliang
  • 749
  • 5
  • 7
  • Even though a similar answer has been posted already: +1 for inheriting from QWidget when using Q_OBJECT, as the macro will not work when not inheriting from QObject or any of its subclasses – Tim Meyer Apr 18 '12 at 11:25