Qt connect signal to slot
I have a main window class which contains a QSplitter widget (among other
widgets). The contents of this splitter are populated by the widgets that
are in another class.
the header of the other class looks like this:
class: other_class public: QWidget
{
Q_OBJECT
public:
other_class();
QWidget *other_widget;
QPushButton *test_btn;
public slots:
test_function();
}
I populate the splitter using:
other_class oc_point;
splitter->addWidget(oc_point.otherWidget);
inside this other Widgit I have a layout with a QPushButton called
test_btn added I also have a function defined in the header file under
public slots: called test_function which has the corresponding code in the
cpp file:
cout << "Test!" << endl;
I try and call this function using the following code:
connect(test_btn, SIGNAL(clicked()), SLOT(test_function()));
The widgets and buttons appear as expected in the application but when I
click it nothing happens.
If I add the same connect code to the main window it works (for calling a
test function from the main window) i.e.
connect(cc_point.test_btn, SIGNAL(clicked()),
SLOT(main_win_test_function()));
I cant call the test function from the other class unless I call it from
the main_win_test_function()
I know I'm missing the 'receiver widget' from the connect statement,
although it does work without it in the main window class and I don't get
any errors when compiling.
Do I need to define the parent or something in the other_class?
Any help with this would be much appreciated. Let me know if I need to add
more of my code, or I need to explain my problem better.
Thanks in advance.
Question EDIT, Code:
main_window.cpp:
main_window::main_window()
{
add_splitter();
QGridLayout *window_layout = new QGridLayout;
window_layout->setSpacing(0);
window_layout->setContentsMargins(0, 0, 0, 0);
window_layout->addWidget(splitter1, 0, 0);
set_layout(window_layout);
}
void main_window::add_splitter()
{
other_class oc_point;
splitter1 = new QSplitter(Qt::Horizontal);
splitter1->addWidget(oc_point.oc_widget);
}
other_class.cpp:
other_class:other_class()
{
oc_widget = new QWidget;
QGridLayout *other_layout = new QGridLayout(oc_widget);
test_btn = new QPushButton;
test_btn->setText("Test Button");
connect(test_btn, SIGNAL(clicked()), test_btn->parent(),
SLOT(test_function());
other_layout->addWidget(test_btn);
}
void other_class::test_function()
{
cout << "Test output" << endl;
}
main.cpp:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
main_window window;
window.resize(1100, 700);
window.setWindowTitle("Qt Test");
window.setWindowIcon(QIcon (":/images/icon_1.png"));
window.setMinimumHeight(500);
window.show();
return app.exec();
}
As I mentioned above, this all works fine as far as the window getting
created and the widgets being displayed goes, but the test_function
doesn't get called when I click the button. Let me know if I need to
include my header files as well.
No comments:
Post a Comment