PDA

View Full Version : Access widget inside the QMainWindow centralwidget



graciano
23rd January 2014, 16:31
Hi
I'm trying to connect a button that is inside a widget(myCentralWidget). This widget is set as the QMainWindow central widget.
This is an example:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
widget = new myCentralWidget(this);
setCentralWidget(widget);
// ...
}

All classes are created using Qt Designer Form class from Qt Creator: MainWindow and myCentralWidget.
How do i connect a button that is inside the ui of the myCentralWidget to make something happen in the qmainwindow?
Thanks

anda_skoa
23rd January 2014, 16:56
The cleanest way is to forward the signal in myCentralWidget so that the myCentralWidget class has a signal you can connect to in MainWindow.

So you declare a signal in myCentralWidget


class myCentralWidget : public QWidget
{
Q_OBjECT
public:
// ...

signals:
void someButtonClicked(); // or use a name that indicates that the user wants to do
};

and forward the button's signal, e.g. in the constructor


connect( ui->someButton, SIGNAL(clicked()), this, SIGNAL(someButtonClicked()) );


Cheers,
_

graciano
23rd January 2014, 18:21
Still don't get it ... i will take a better look at this: https://qt-project.org/doc/qt-5/signalsandslots.html
Never tried to forward a signal before :o

anda_skoa
23rd January 2014, 19:48
When the button is clicked, it emits its clicked() signal.
Due to the signal/signal connect the container widget's someButtonClicked() signal is now also emitted.

In MainWindow you have the object of the container widget, so you can connect its someButtonClicked() signal just like if it where the button.

Cheers,
_

graciano
23rd January 2014, 21:40
I get it ... and it is simple after all.
Thanks for the patience anda_skoa.
I attach example: 9971