vendredi 7 septembre 2018

create widget inside a function of a class

I'm inside a class which deals with a simple window (I'm starting with Qt) but when I try to add a new Widget (from a slot of the custom class) to this window, it doesn't appear on the window. I use QTextStream which shows that the slot is correctly called and the random coordinates generated are rights so I totally do not understand why there is nothing new on my window. Moreover, the first time the slot is called as a function in the ButtonsWindow::ButtonsWindow(QWidget *parent) : QWidget(parent) {}, the widget appears correctly... Do you have any ideas ?

Here is my .h code :

#ifndef BUTTONSWINDOW_H
#define BUTTONSWINDOW_H

#include <QPushButton>
#include <QGridLayout>
#include <QLabel>
#include <cstdlib>
#include <ctime>
#include <QDebug>
#include <QVector>

class ButtonsWindow : public QWidget
{
    Q_OBJECT
public:
    explicit ButtonsWindow(QWidget *parent = nullptr);

private:
    QPushButton *testButton;
    QVector<QWidget*> buttonsArray;
signals:

public slots:
    void createNewButton();
}; 

#endif // BUTTONSWINDOW_H

Here is my .cpp class code :

#include "buttonswindow.h"

ButtonsWindow::ButtonsWindow(QWidget *parent) : QWidget(parent)
{
    setFixedSize(1000, 300);
    createNewButton();
}

void ButtonsWindow::createNewButton()
{
QWidget *mainWidget = new QWidget(this);
QPalette pal = palette();
pal.setColor(QPalette::Background, Qt::lightGray);
mainWidget->setAutoFillBackground(true);
mainWidget->setPalette(pal);
QGridLayout *layout =  new QGridLayout;

QLabel *text = new QLabel("What to do?");
text->setCursor(Qt::WhatsThisCursor);
QPushButton *addWidget = new QPushButton("Create a new Button");
QObject::connect(addWidget, SIGNAL(pressed()), this, SLOT(createNewButton()));
addWidget->setCursor(Qt::CrossCursor);
QPushButton *removeWidget = new QPushButton("Remove an existing random Button");
removeWidget->setCursor(Qt::ForbiddenCursor);

layout->addWidget(text, 0, 0, 1, 2, Qt::AlignCenter);
layout->addWidget(addWidget, 1, 0, 1, 1, Qt::AlignCenter);
layout->addWidget(removeWidget, 1, 1, 1, 1, Qt::AlignCenter);

mainWidget->setLayout(layout);

int nX = (rand() % this->width() - 2 * mainWidget->width());
nX += mainWidget->width();
int nY = (rand() % this->height() - 2 * mainWidget->height());
nY += mainWidget->height();
mainWidget->move(nX, nY);
QTextStream(stdout) << "check " << nX << " : : " << nY;
buttonsArray.append(mainWidget);
}

Finnaly, here is my main.cpp code :

#include <QApplication>
#include <QPushButton>
#include "buttonswindow.h"

#include <QGridLayout>

using namespace std;

int main(int argc, char *argv[]) {

    srand(time(0));

    QApplication app(argc, argv);

    ButtonsWindow window;
    window.show();
    return app.exec();
}

Aucun commentaire:

Enregistrer un commentaire