0
votes

I have signal/slot code. I want function on another class to work when checkbox is being toggled. I wrote the following code. Signal/Slot is working properly on Debug mode. However, it does not work on Release mode.

I also want my program to works dynamically. I do not need to open a new window.

Here is my code. Thank you in advance.

preferences.cpp

Projects *projects;
// projects = new Projects; // I dont want to create new one. I just want to make changes on the existing Mainwindow (Projects class)

connect(ui->checkBox_toolbar, SIGNAL(toggled(bool)), projects, SLOT(hide_toolbar(bool)));
connect(ui->checkBox_button, SIGNAL(toggled(bool)), projects, SLOT(hide_buttons(bool)));

projects.cpp

void Projects::hide_toolbar(bool checked)
{
    ui->toolBar->setVisible(checked);
}

I have got warning: 'projects' may be used uninitialized in this function [-Wmaybe-uninitialized] connect(ui->checkBox_toolbar, SIGNAL(toggled(bool)), projects, SLOT(hide_toolbar(bool)));

And error: "QObject::connect: Cannot connect QCheckBox::toggled(bool) to (null)::hide_toolbar(bool)"

2
What "does not work" mean exactly ? Also, please use pointer syntax to make connections, it helps finding errors: connect(ui->checkBox_toolbar, &QCheckbox::toggled, projects, &Projects::hide_toolbar); - Benjamin T
A program that works in debugging mode but fails in release mode is often caused by a bad operation on a pointer (dereferencing a null, falling off the end of an array, using an uninitialised pointer, etc etc). The code you have provided doesn't provide any useful information about the cause - the best you can hope for without a minimal reproducible example is general advice (like I've given) or guesswork (about behaviour of code you haven't shown). - Peter
signal/slot does not work properly on Release mode. I have got error: "QObject::connect: Cannot connect QCheckBox::toggled(bool) to (null)::hide_toolbar(bool)" - redrussianarmy
And I have this warning: 'projects' may be used uninitialized in this function [-Wmaybe-uninitialized] connect(ui->checkBox_toolbar, SIGNAL(toggled(bool)), projects, SLOT(hide_toolbar(bool))); - redrussianarmy

2 Answers

2
votes

The warning tells you exactly what is wrong. The projects pointer variable is uninitialized. It does not point to a valid Projects object. You cannot use it like that, that’s undefined behaviour. That it seems to work in debug mode is pure coincidence.

Your commented out code says something about the existing main window. If you want to connect to a slot of that main window, you need to get a pointer to that main window object first. Then you can connect.

0
votes

Thank you all for your interest.

I handled with the following code:

Projects *projects = qobject_cast<Projects *>(parent);