Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to change button position in a run time?



  • Hello,

    I'm new to QT and I want to know, how to change button position in a run time? Plus, how can I change position inside a method of MainWindow while a button was created in a constructor?


  • Qt Champions 2017

    use button.setGeometry(x,y,width,height) method to position.


  • Lifetime Qt Champion

    Hi and welcome to the forums.

    To do as you ask, would be something like

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    
    namespace Ui {
    class MainWindow;
    }
    
    #include <QPushButton>// so it knows type
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    public slots: // notice this. it makes it a slot
        void buttonClicked(); // to be called when clicked
    private:
        Ui::MainWindow *ui;    
        QPushButton *button=NULL; // the button must be a member to be used from other functions in mainwin
    };
    
    #endif // MAINWINDOW_H
    
    

    and in .cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget* parent) :
      QMainWindow(parent),
      ui(new Ui::MainWindow) {
      ui->setupUi(this);
    
      // create button
      button = new QPushButton("Click me", this);
      // hook up its clicked signal to a function in main
      connect(button, &QPushButton::clicked, this, &MainWindow::buttonClicked);
      // move and resize it
      button->setGeometry(100, 100, 50, 50);
      // and show it
      button->show();
    }
    
    void MainWindow::buttonClicked() {
      // move to random position.
      button->move( rand() % 200, rand() % 200);
    }
    

    runnable project to play with
    https://www.dropbox.com/s/3l21boazu2uhpfl/MyFirstButtons.zip?dl=0

    Result:
    alt text


Log in to reply