Cjueden
Cjueden

Reputation: 1200

QtPushButton wont click

Hello Im working through Qt tutorials I've have copy the code for the communicate section of this tutorial. the code compiles and shows but none of my buttons are clickable.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
class QPushButton;
class QLabel;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    void OnPlus();
    void OnMinus();
private:
    Ui::MainWindow *ui;
    QLabel *label;
};

#endif // MAINWINDOW_H

mainwindow.cpp

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


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QPushButton *plus = new QPushButton("+", this);
    plus->setGeometry(50, 40, 75, 30);

    QPushButton *minus = new QPushButton("-", this);
    minus->setGeometry(50, 100, 75, 30);

    label = new QLabel("0", this);
    label->setGeometry(190, 80, 20, 30);

    connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus()));
    connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));

    ui->setupUi(this);
}


void MainWindow::OnPlus()
{
  int val = label->text().toInt();
  val++;
  label->setText(QString::number(val));
}

void MainWindow::OnMinus()
{
  int val = label->text().toInt();
  val--;
  label->setText(QString::number(val));
}


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

main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QPushButton>
#include <QLabel>

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

    return app.exec();
}

Upvotes: 1

Views: 148

Answers (1)

RA.
RA.

Reputation: 7777

Your problem is with this line:

ui->setupUi(this);

It creates an invisible central widget for your main window, which blocks all events destined for your buttons, which is why they don't depress when you click them. Move this line to the beginning of your constructor for MainWindow and the problem will go away.

Upvotes: 5

Related Questions