My app hangs when i try custom slots



  • With that really simple code the app hangs when i click the button, but the examples included in QT works fine, and i don't see differences. I've tryed using different widgets with and without layouts, tryed deriving from QFrame, using "QObject::connect" and "connect" alone, with and without Q_OBJECT macro, but still the same. The only way it works is with an empty slot function. I've tryed with normal SIGNALS and SLOTS and it works. I think it must be a really stupid thing, but i can't see it.

    This is the error when windows forces the exit of the program:
    "Starting C:\Users\Administador\untitled1-build-desktop-Qt_4_8_1_for_Desktop_-MinGW__Qt_SDK__Debug\debug\untitled1.exe...
    The program has unexpectedly finished.
    C:\Users\Administador\untitled1-build-desktop-Qt_4_8_1_for_Desktop
    -_MinGW__Qt_SDK__Debug\debug\untitled1.exe exited with code -1073741819"

    widget.h
    @#ifndef WIDGET_H
    #define WIDGET_H

    #include <QWidget>
    #include <QPushButton>

    class Widget : public QWidget
    {
    Q_OBJECT
    public:
    explicit Widget(QWidget *parent = 0);
    private:
    QPushButton *button;

    signals:

    public slots:
    void slotprueba();

    };

    #endif // WIDGET_H
    @

    widget.cpp
    @#include "widget.h"

    Widget::Widget(QWidget *parent) :
    QWidget(parent)
    {
    QPushButton *button=new QPushButton("HOLA",this);
    QObject::connect(button,SIGNAL(clicked()),this,SLOT(slotprueba()));

    }
    void Widget::slotprueba(){
    button->setText("Pulsado");
    }
    @

    main.cpp
    @#include <QtGui/QApplication>
    #include "widget.h"

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    Widget wid;

    wid.show();
    
    
    return a.exec&#40;&#41;;
    

    }
    @



  • Try to write such slot:

    @void Widget::slotprueba(){
    if(button)
    button->setText("Pulsado");
    }@

    Looks like "button" isn't initialized.

    Edit: the problem is that you redefined your button in constructor. Just write:
    @button = new QPushButton("Text", this);@



  • The actual pointer to the button you are connecting the slot to is lost after the constructor, and the one in the header points to nothing.



  • Ok, solved. The problem was the second redefinition of the widget. Thanks to both.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.