QWidget通过一个插槽

QWidget through a slot

我正在尝试创建一个函数,该函数将根据传递给它的 QWidget 显示一个小部件。

我有:

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

当我点击按钮时没有任何反应,它出现了 'No such slot MainWindow::ShowScreen(timing_screen)'

如果 showScreen 在您的 mainwindow.h 中声明为 Qt Slot,例如:

private slots:
    void showScreen(QWidget* w);

并且您的信号在 buttons_widget

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

然后您可以将该信号连接到插槽。请注意,信号和槽的参数必须匹配。 即:"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*)));

并且您必须从 buttons_widget 中发出 position_screentiming_screen,例如:

emit showPositionScreen_signal(position_screen);

正如 thuga 所指出的,这意味着您不需要两个不同的信号。要将另一个 QWidget 传递到同一个插槽,只需用它发出该信号即可。即:

emit showPositionScreen_signal(timing_screen);

然后我建议将您的信号名称更改为合适的名称。