1

How can I do this? I want to create a button by pressing another button, but in the current code of my, I can just create one button and the button I've created it, dissapears.

How could i dynamically do this? Pls help, I'm kinda new to Qt.

That's the main part of it:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->button1->setVisible(false);
}

MainWindow::~MainWindow() {
    delete ui; }


void MainWindow::on_multiplyButton_clicked()
{
    ui->button1->setVisible(true);
}

In this way the button just appears, but that doesn't seem like a solution to me, if i would want to scale it. enter image description here

With every click on the multiply a new button should appear.

3
  • You should edit your question with your current code so we can better understand your problem (see MCVE) Commented Aug 4, 2016 at 7:52
  • You're right, is it more understandable now? Commented Aug 4, 2016 at 8:03
  • Note that you shouldn't be using QMainWindow unless you need the dockable subwindow functionality it offers. You should otherwise use a QDialog or QWidget as the base class. Commented Aug 4, 2016 at 13:24

1 Answer 1

1

I'm not familiar with the designer and ui files. Here is a "full code" proposition:

class MainWindow : public QMainWindow {
    public:
        MainWindow(QWidget *parent = nullptr);

        void on_multiplyButton_clicked();

    private:
        QBoxLayout *layout;
};

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent) {
    // create multiply button
    QPushButton *button = new QPushButton(tr("Push me hard"));
    connect(
        button, &QPushButton::clicked,
        this  , &MainWindow ::on_multiplyButton_clicked
    );

    // initialize button container
    this->layout = new QHBoxLayout; // or QVBoxLayout if you prefer
    this->layout->addWidget(button);

    // set central widget of the main window
    QWidget *central_widget = new QWidget;
    central_widget->setLayout(this->layout);
    this->setCentralWidget(central_widget);
}

void MainWindow::on_multiplyButton_clicked() {
    QPushButton *button = new QPushButton(
        tr("button%1").arg(this->layout->count())
    );
    this->layout->addWidget(button);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.