Search code examples
qtsignalssignals-slotsqwidgetqt-signals

QWidget through a slot


I'm trying to make a function that'll show a widget depending on the QWidget passed to it.

I have:

position_widget = new positionWidget();
timing_widget = new timingWidget();
...

void MainWindow::showScreen(QWidget *w)
{
    ui->screenWidget->layout()->addWidget(w);
    w->show();
}


void MainWindow::doConnects()
{
QObject::connect(buttons_widget, SIGNAL(showPositionScreen_signal()), this, SLOT(showScreen(position_screen)));
QObject::connect(buttons_widget, SIGNAL(showTimingScreen_signal()), this, SLOT(showScreen(timing_screen)));
}

Nothing happens when I click the button and it comes up with 'No such slot MainWindow::ShowScreen(timing_screen)'


Solution

  • If showScreen is declared as Qt Slot in your mainwindow.h like:

    private slots:
        void showScreen(QWidget* w);
    

    And your Signals are declared in buttons_widget

    signals:
        void showPositionScreen_signal(QWidget* w); //Note that signal needs same type as slot
        void showTimingScreen_signal(QWidget* w);
    

    Then you can connect that signal to a slot. Note that the arguments of signals and slots have to match. I.e: "The signals and slots mechanism is type safe: 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.)"

    connect(buttons_widget, SIGNAL(showPositionScreen_signal(QWidget*)), this, SLOT(showScreen(QWidget*)));
    

    And you will have to emit position_screen and timing_screen from within buttons_widget like:

    emit showPositionScreen_signal(position_screen);
    

    As thuga pointed out, it is to say that you do NOT need two different signals. To pass another QWidget to the same slot simply emit that signal with it. I.e.:

    emit showPositionScreen_signal(timing_screen);
    

    And i would suggest to change the name of your signal to something appropriate then.