Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to add slot for a button press ?



  • Hi ,

    I want to execute a function whenever the button is pressed.
    I am not using QtGui.

    I have an application and i am trying to manipulate the application with the help of Qt (In this case - whenever i click the button , a signal should generate and in turn execution of slot should take place )

    The code looks like this

    #includes <....>
    #includes <.....>
    ......
    
    void execute_this();
    
    int main()
    {
    
    ...
    ...
    QMainWindow mainWin;
    myApp.setMainWindow(&mainWin);
    QPushButton *button = new QPushButton(&mainWin);
    button->setText("Button");
    // QObject::connect(button, SIGNAL(clicked()), &mainWin, SLOT(execute_this()));
    mainWin.showNormal();
    ...
    ...
    ...
    
    return myApp.exec();
    }
    
    void execute_this()
    {
    std::cout<<"Sample text \n";
    }
    

    How to execute a function whenever i press a button in the Qmainwindow ?

    Please help


  • Qt Champions 2017

    This should work fine. Hope execute_this function is slot in inside your class. What do you mean by not using QtGui ? Without using this you will not be able to create the button or main window objects


  • Lifetime Qt Champion

    @BhanuKiranChaluvadi execute_this has to be a slot. A slot is a method in a class which is derived from QObject and has Q_OBJECT macro. Please take a look at http://doc.qt.io/qt-4.8/signalsandslots.html This is a basic concept in Qt which you should know if you want to use Qt.
    What do you mean by "I am not using QtGui"? If you use QMainWindow and QPushButton then you use GUI.



  • @jsulm
    @dheerendra

    Thank you very much for the reply.

    I have gone through the documentation and was able to solve the issue..
    The process involved creating a creating a moc file and including in my visual studio project.



  • @BhanuKiranChaluvadi

    if the topic is solved make the thread as solved , which will be usefull.
    Cheers,
    Thanks.


Log in to reply