I am using Qt5 on Windows7 and I recently found an interesting Qt example code.
Basically, it looks like this:
ButtonWidget::ButtonWidget(const QStringList &texts, QWidget * parent)
: QWidget(parent)
{
signalMapper = new QSignalMapper(this);
QGridLayout * gridLayout = new QGridLayout;
for (int i = 0; i < texts.size(); ++i)
{
QPushButton * button = new QPushButton(texts[i]);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(button, texts[i]);
gridLayout->addWidget(button, i / 3, i % 3);
}
connect(signalMapper, SIGNAL(mapped(QString)), this, SIGNAL(clicked(QString)));
setLayout(gridLayout);
}
It is a nice and useful example, but it doesn't have a proper destructor... just in case I want to delete an object of ButtonWidget
type, or if I want to customise the code to be able to remove/add widgets. The idea is how to delete all objects created in the constructor (dynamically, using new
).
My approach was to use a private variable QList<QPushButton*> list
, add all new-allocated buttons to list (in the constructor) and delete them one-by-one in the destructor, using the above list
. But it seems so kindergarten-approach.
I think there must be some other way, better way to do it, without a list and without messing the constructor code :) Thanks for your time and patience!