Important: Please read the 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
        explicit MainWindow(QWidget *parent = 0);
    public slots: // notice this. it makes it a slot
        void buttonClicked(); // to be called when clicked
        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) :
      ui(new Ui::MainWindow) {
      // 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
    void MainWindow::buttonClicked() {
      // move to random position.
      button->move( rand() % 200, rand() % 200);

    runnable project to play with

    alt text

Log in to reply