Qt Tutorials For Beginners – Adding Click Event to QPushbutton Example




Qt Tutorials For Beginners
Qt Tutorials For Beginners

In this post we will see how to add the click event to the QPushbutton with an example.

samples.pro

TARGET = Sample

QT = core gui
CONFIG += c++11
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
SOURCES += \
    main.cpp

HEADERS += \
    MyMainWindow.h

MyMainWindow.h

#ifndef MYMAINWINDOW_H
#define MYMAINWINDOW_H
#include <QPushButton>
#include <QMessageBox>
#include <QMainWindow>
#include <QVBoxLayout>

class MyMainWindow: public QMainWindow
{
  Q_OBJECT

public:
  MyMainWindow(){}
  ~ MyMainWindow(){}

  void Execute()
  {

    QPushButton *button = new QPushButton(this);
    QPushButton *button2 = new QPushButton(this);

    button->setText("Button No. 1");
    button2->setText("Button No. 2");

    QObject::connect(button, SIGNAL(clicked()),this, SLOT(clickedSlot()));
    QObject::connect(button2, SIGNAL(clicked()),this, SLOT(clickedSlot()));

    button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    button2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    QWidget* centralWidget = new QWidget(this);
    centralWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    QVBoxLayout* layout = new QVBoxLayout(centralWidget);

    layout->addWidget(button);
    layout->addWidget(button2);

    setCentralWidget(centralWidget);
    setWindowTitle("Pushbutton Clicked Signal Test");
    show();
  }

public slots:
  void clickedSlot()
  {
    QMessageBox msgBox;
    msgBox.setWindowTitle("MessageBox Title");
    msgBox.setText("You Clicked "+ ((QPushButton*)sender())->text());
    msgBox.exec();
  }
};
#endif // MYMAINWINDOW_H

main.cpp

#include <QApplication>
#include <QMainWindow>
#include "MyMainWindow.h"

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  MyMainWindow window;

  window.setWindowTitle(QString::fromUtf8("MainWindow"));
  window.resize(450,300);
  window.Execute();

  return app.exec();

}

OUTPUT

Adding Click Event to QPushbutton Example Output
Adding Click Event to QPushbutton Example Output

Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





1 Comment

Leave a Reply

Your email address will not be published.


*