Слот Qt не вызывается

Я сократил код.
У меня есть главное окно с кнопкой. Кнопка открывает другое окно для регистрации чьей-либо личной информации.
Когда я нажимаю «Подтвердитель», он должен запускать слот подтверждения информации (). Однако ничего не происходит.
Не понимаю, почему. У меня нет журнала ошибок.

Извините за огромный код, но эта проблема сводит меня с ума. Я не понимаю, почему слот в первом окне работает, хотя слот во втором окне с точно таким же синтаксисом не запускает метод confirmerInformations

main.ccp

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

    Principale fenetrePrincipale;
    fenetrePrincipale.show();

    return app.exec();
}

Principale.h

#ifndef PRINCIPALE_H
#define PRINCIPALE_H

#include<QApplication>
#include<QPushButton>
#include<QBoxLayout>
#include<QGroupBox>


#include"Inscription.h"
#include"Connexion.h"

class Principale: public QWidget
{
    Q_OBJECT
public:
    Principale();
public slots:
    void inscription();
    void connexion();

private:
    QPushButton * boutonInscription;
    QVBoxLayout * vboxPrincipale;
    QVBoxLayout * layoutPrincipal;
    QGroupBox * general;
    QGroupBox* groupPrincipal;


};
#endif // PRINCIPALE_H

Principale.cpp

Principale::Principale()
    {
        setFixedSize(250, 150);
        boutonInscription = new  QPushButton("Ouvrir un nouveau compte bancaire");
        vboxPrincipale = new QVBoxLayout;

        vboxPrincipale->addWidget(boutonInscription);

        general = new QGroupBox("Cliquez sur un bouton");
        general->setLayout(vboxPrincipale);

        layoutPrincipal = new QVBoxLayout;
        layoutPrincipal->addWidget(general);

        setLayout(layoutPrincipal);
        setWindowTitle("Bienvenue dans votre banque");

        connect(boutonInscription, SIGNAL(clicked()), this, SLOT(inscription()));


    }

    void Principale::inscription()
    {

        Inscription *uneInscription = new Inscription();
        uneInscription->show();

    }

Надпись.h

#ifndef INSCRIPTION_H
#define INSCRIPTION_H
#include<QWidget>
#include<QLineEdit>
#include<QPushButton>
#include<QGroupBox>
#include<QBoxLayout>
#include<QLabel>
#include<QFormLayout>

    class Inscription : public QWidget
    {
        Q_OBJECT

    public:
        Inscription();
    private:
        // Information personnellses
        QGroupBox* boxInformationsPersonnelles_;
        QFormLayout* formInformationsPersonnelles_;
        QLabel* labelNom_;
        QLineEdit* nom_;


        // Boutons
        QGroupBox* boxBoutons_;
        QHBoxLayout* layoutBoutons_;
        QPushButton* boutonConfirmation_;

        //Layout principal
        QVBoxLayout* layoutPrincipal_;

    public slots:
        void confirmerInformations();
    };

Inscription.cpp

#include"Inscription.h"
#include<QErrorMessage>
#include<QDebug>

Inscription::Inscription(){

    // Box Informations personnelles
        labelNom_ = new QLabel("Nom :");
        nom_ = new QLineEdit();

        boxInformationsPersonnelles_ = new QGroupBox("Vos informations personnelles");
        boxInformationsPersonnelles_->setLayout(formInformationsPersonnelles_);

     // Box boutons
        boutonConfirmation_ = new QPushButton("Confirmer");

        layoutBoutons_ = new QHBoxLayout();
        layoutBoutons_->addWidget(boutonConfirmation_);

        boxBoutons_ = new QGroupBox("Confirmation");
        boxBoutons_->setLayout(layoutBoutons_);


     // Layout principal
        layoutPrincipal_ = new QVBoxLayout();
        layoutPrincipal_->addWidget(boxInformationsPersonnelles_);
        setLayout(layoutPrincipal_);


    // Connexion des boutons
        boutonConfirmation_ = new QPushButton("Confirmer");

        connect(boutonConfirmation_, SIGNAL(clicked()), this, SLOT(confirmerInformations()));

}

//Slots

void Inscription::confirmerInformations(){
        QErrorMessage* erreurInformationsPersonnelles = new QErrorMessage();
        erreurInformationsPersonnelles->showMessage("Veuillez remplir toutes vos informations personnelles");

}

person singe3    schedule 03.12.2014    source источник


Ответы (1)


Вы выделяете память дважды.

boutonConfirmation_ = new QPushButton("Confirmer");
//...
boutonConfirmation_ = new QPushButton("Confirmer");//why?

Удалите одну строку.

Объяснение. Я хочу добавить короткий код, который вы можете легко скомпилировать на своей машине и показать проблему:

QPushButton *ptr;           //just pointer
ptr = new QPushButton(this);//allocate memory, this is a parent
ptr->setObjectName("ptr");  //object name to find it in future
qDebug() << ptr;            //show ptr
ptr = new QPushButton;      //allocate memory again, but without parent
qDebug() <<  connect(ptr,SIGNAL(clicked()),this,SLOT(echo()));
                            //show that connection was succesfull
qDebug() << "new ptr"<< ptr << "old ptr" << this->findChildren<QPushButton *>("ptr");
                            //show new and old ptrs

Выход:

QPushButton(0x28d726a8, name = "ptr") //our old ptr
true                                  //connection succesfull
new ptr QPushButton(0x28d726e8) old ptr (QPushButton(0x28d726a8, name = "ptr") )
//pay attention that new ptr and old has different adresses and names, it is 2 different buttons.

Вывод: в вашем коде вы используете старую кнопку, которая не была подключена, поэтому ваш слот никогда не вызывает.

person Kosovan    schedule 03.12.2014
comment
Не могли бы вы добавить логику в свой ответ, почему это происходит? Короче говоря, layoutBoutons_->addWidget(boutonConfirmation_); добавлял утечку указателя в пользовательский интерфейс, и было установлено соединение с переопределенным указателем. - person lpapp; 03.12.2014
comment
Конечно, не торопитесь. Это может быть вызвано тем, что у читателей не создастся неправильного впечатления от создания этой двойной конструкции самостоятельно. Спасибо. :) - person lpapp; 03.12.2014
comment
@lpapp Уже сделано. Я добавил короткий компилируемый код и объяснение - person Kosovan; 03.12.2014