Virgil Sébirot
Virgil Sébirot

Reputation: 13

Class inherited from QPushbutton shows no text

I'm trying to create a first project using qt (a simple calculator). I created a class who inherits from QPushButton, code compiles without warning, but the button created appears empty. I don't understand why it's not showing 42...

Here's the code :

main.cpp :

#include "bouton_chiffre.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    bouton_chiffre w(42, 0);
    w.show();

    return a.exec();
}

bouton_chiffre.h :

#ifndef BOUTON_CHIFFRE_H
#define BOUTON_CHIFFRE_H

#include <QObject>
#include <QWidget>
#include <QPushButton>

class bouton_chiffre : public QPushButton
{
    Q_OBJECT

public:
    bouton_chiffre(int, QWidget*);

private:
    int valeur_du_bouton;
    QPushButton *le_bouton;
};

#endif // BOUTON_CHIFFRE_H

bouton_chiffre.cpp :

#include "bouton_chiffre.h"

bouton_chiffre::bouton_chiffre(int valeur_init, QWidget *parent)
{
    valeur_du_bouton = valeur_init;
    le_bouton = new QPushButton(QString::number(valeur_init), parent);
}

Upvotes: 1

Views: 1646

Answers (2)

Virgil S&#233;birot
Virgil S&#233;birot

Reputation: 13

So, I was both inheriting from and creating a QPushButton, which of course does not works well... I modified boutonchiffre.cpp as follows, it works as I expected now :

#include "bouton_chiffre.h"

bouton_chiffre::bouton_chiffre(int valeur_init, QWidget *parent) : QPushButton(parent)
{
    valeur_du_bouton = valeur_init;
    setText(QString::number(valeur_init));
}

Using the QPushButton constructor directly instead of setText is maybe more elegant though, I'll probabily do that.

Thank you all for your answers !

Upvotes: 0

ftynse
ftynse

Reputation: 797

You are not setting up the text for the parent button class, but creating a new instance of this class in le_bouton.

Do something like this in constructor:

bouton_chiffre::bouton_chiffre(int valeur, QWidget *parent)
  : QPushButton(QString::number(valeur), parent)
{ 
  /*...*/
}

You should read more about how inheritance work. In the derived class, you have access to all protected and public members of the base class, so setText(QString::number(valuer)); would also work. In general case, however, you may call the base class constructor from the initialization list (after colon) of the derived class and pass the required arguments.

Creating a member of the derived class that has the type of the base class has nothing to do with inheritance. It's just a different object.

Upvotes: 2

Related Questions