There are a few issues with the code you provided in Code 2:
In the first loop, you are trying to access the widget member of the signalMapper object, but this object does not have a widget member. You need to use MyForm::getMyForm() to get a pointer to the main window widget and then use that to call findChild.
The findChild method returns a QObject*, which you are trying to cast to a QPushButton*. However, this is not guaranteed to work, because findChild might return a pointer to a different type of widget. You should use the qobject_cast function to safely cast the returned pointer to a QPushButton*.
You are using the + operator to concatenate strings in the findChild method calls, but this operator is not defined for strings in C++98. You should use the std::stringstream class or the sprintf function to construct strings with variable parts.
Here is a fixed version of your code where these issues are fixed, and that should make Code 2 work:
#include <QMainWindow>
#include <QSignalMapper>
#include <QPushButton>
#include <QLabel>
#include <sstream>
void Display::setting_Style()
{
signalMapper = new QSignalMapper(MyForm::getMyForm());
for (int i = 1; i <= 5; ++i)
{
std::stringstream ss;
ss << "BTN_FUN" << i << "_TEL";
QPushButton* btn = qobject_cast<QPushButton*>(MyForm::getMyForm()->findChild<QObject*>(ss.str().c_str()));
if (btn)
{
btn->setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;");
signalMapper->setMapping(btn, btn);
}
}
for (int i = 1; i <= 5; ++i)
{
std::stringstream ss;
ss << "LBL_FUN" << i << "_TEL";
QLabel* btn = qobject_cast<QLabel*>(MyForm::getMyForm()->findChild<QObject*>(ss.str().c_str()));
if (btn)
{
btn->setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;");
signalMapper->setMapping(btn, btn);
}
}
}
This code should fix the segmentation fault error and apply the desired style sheet to the buttons and labels.