Home > Software engineering >  How to instantiate a pushbutton from ui into the code in QT framework
How to instantiate a pushbutton from ui into the code in QT framework

Time:09-02

What I intent to do is just a basic animation in my qt application. For the animation, when the button is clicked, I want it to go from one point to another in a time interval. Here is my code (main.cpp and mainWindow.h are the same as default. ):

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPropertyAnimation>

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

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

void MainWindow::on_pButton_clicked()
{
    QPushButton* pb = ui->pButton;
    QPropertyAnimation anim(pb, "geometry");
    anim.setStartValue(QRect(100,100,100,30));
    anim.setEndValue(QRect(900,900,100,30));
    anim.setDuration(10000);
    anim.start();
}

Build works with no errors. The problem is, when I click the button, its position properties just transforms to the startvalues but stays there instead of moving to the endpoint. Why it remains stationary?

And, lastly, my other question is how can I get a reference of a widget that I created on ui design. I know one way which I used in my code, getting the button using ui->pButton. But in this way I must create the QPushButton variable as a pointer. Is there any way I can reference a button into code which was added to ui using ui designer (not using code to generate).

CodePudding user response:

You are declaring the anim object as local variable. As soon as on_pButton_clicked() function exits, anim variable will get destroyed. Create anim object on the heap, as shown below, then your code should work fine.

void MainWindow::on_pButton_clicked()
{
    QPropertyAnimation *anim = new QPropertyAnimation(ui->pButton, "geometry");
    anim->setEndValue(QRect(900,900,100,30));
    anim->setEndValue(QRect(500,500,100,30));
    anim->setDuration(10000);
    anim->start(QAbstractAnimation::DeleteWhenStopped);
}

enter image description here

  •  Tags:  
  • c qt
  • Related