Hi everyone I'm pretty new to programming with Qt and I would like to create a widget using a QStackedLayout. I already designed some widgets with Qt Creator, added them to the QStackedLayout and set it to the main widget. But now I would like to change the widgets using buttons inside the added widgets using the setCurrentIndex method. Now I have to use the connect function but in the main widget class I can't access components from the other widgets to connect them. So how can I do this?
#include "mainwindowwidget.h"
#include "ui_mainwindowwidget.h"
MainWindowWidget::MainWindowWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWindowWidget)
{
qApp->setStyleSheet("MainWindowWidget {background-color : red}");
//initializing widgets
this->mainWidget_ = new MainWidget;
this->createGameWidget_ = new CreateGameWidget;
this->widgets_ = new QStackedLayout;
//adding widgets to QstackedLayout
this->widgets_->addWidget(this->mainWidget_);
this->widgets_->addWidget(this->createGameWidget_);
this->setLayout(this->widgets_);
this->showFullScreen();
// I would like to connect the qstackedlayout
// = widgets_ with a button placed in mainwidget_
ui->setupUi(this);
}
MainWindowWidget::~MainWindowWidget()
{
delete ui;
}
You have a few options here. If your button is a public member of MainWidget, then you can simply connect the button's clicked() signal to your slot in MainWindow.
//mainwindow.h
...
public slots:
void buttonClicked();
//mainwindow.cpp
...
connect(mainWidget_->button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
...
void buttonClicked()
{
//do what you want to do here...
}
Another option is to create a custom signal in your MainWidget class. Then connect your button's clicked() signal to this custom signal:
//mainwidget.h
...
signals:
void buttonClickedSignal();
//mainwidget.cpp
connect(button, SIGNAL(clicked()), this, SIGNAL(buttonClickedSignal()));
Then connect your buttonClickedSignal() signal to a slot in your MainWindow:
//mainwindow.cpp
connect(mainWidget_, SIGNAL(buttonClickedSignal()), this, SLOT(buttonClicked()));
A third option would be to add a function to your MainWidget class, that returns a pointer to your button. Then call this function in your MainWindow class, and use that pointer to connect your button to a slot.
//mainwidget.h
...
public:
QPushButton* getButton();
...
//mainwdiget.cpp
...
QPushButton* getButton()
{
return button;
}
...
//mainwindow.cpp
...
QPushButton *button = mainWidget_->getButton();
connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With