I'm pretty new to QT and try to add a button (which emits a signal on click) during runtime. I added a slot for the adding itself but it didn't work. For testing-purposes I've put a printf("Hello World");
in my code to see when the method is called.
Strangely I get my "Hello World" only when I close the program... For testing purposes I've called the add-Method in my main. If I click on the button nothing happens. As I remove it from the main I don't even get that any more...
Maybe someone can tell me what I did wrong?
ButtonCreator.h
QT_BEGIN_NAMESPACE
class QAction;
class QGroupBox;
class QPushButton;
class QVBoxLayout;
class QGridLayout;
QT_END_NAMESPACE
class ButtonCreator : public QWidget {
Q_OBJECT
public:
ButtonCreator();
private:
void createGridGroupBox();
unsigned int buttoncount; //Number of current buttons
QVBoxLayout *mainLayout; //Main Window
QGroupBox *gridGroupBox; //Window with Buttons
QGridLayout *layout; //Button-Layout
QPushButton* getAddButton();
public slots:
int addButton(QIcon *icon = 0); //Add Button
};
ButtonCreator.cpp
#include <QtGui>
#include "ButtonCreator.h"
ButtonCreator::ButtonCreator() {
createGridGroupBox(); //Create Window
mainLayout = new QVBoxLayout;
mainLayout->addWidget(gridGroupBox);
mainLayout->addWidget(getAddButton());
setLayout(mainLayout);
}
void ButtonCreator::createGridGroupBox() {
gridGroupBox = new QGroupBox();
layout = new QGridLayout;
gridGroupBox->setLayout(layout);
}
int ButtonCreator::addButton(QIcon *icon) {
printf("Hello World");
QPushButton *button = new QPushButton();
if (icon != 0) {
button->setIcon(*icon);
}
layout->addWidget(button, 0, buttoncount);
buttoncount++;
button->show(); //Adding that didn't change anything
gridGroupBox->update(); //Adding that didn't change anything
layout->update(); //Adding that didn't change anything
return buttoncount;
}
QPushButton* ButtonCreator::getAddButton() {
QPushButton *addbutton = new QPushButton();
QPixmap pixmap(100, 100);
pixmap.fill(QColor("blue"));
QIcon icon = QIcon(pixmap);
connect(addbutton, SIGNAL(clicked()), this, SLOT(addButton(&icon)));
return addbutton;
}
Related to the Signal I want to add I am a bit confused. It's easy to find how slots are defined but related to Signals I'm even unsure if I understood the difference.
For example if I press a button it sends the absolute number of buttons as Signal. Is it correct to do it like:
ButtonCreator.h
class ButtonCreator : public QWidget {
..
signals:
void getAbsButtons(int anyPara);
..
}
And to add it with:
connect(newButton, SIGNAL(clicked()), this, SLOT(getAbsButtons(para)));
At http://www.qtcentre.org/threads/19493-creating-custom-signal they have a similar discussion. It puzzles me I am treading the Signal like a slot...