Function for setting button text



  • I am using the following code to set the text on a button:

    ui->MyButton_1->setText("ON");

    I would like to create a function to do this with two arguments; a string for the text and the button name. No problem for the text but how can I pass the button name to the function?
    The function would look like this:

    void MainWindow::SetButtonText(QString S, ????)
    {
    ????->setText(S);
    }
    The call would be like this:
    setText("ON" ,????);

    Any advice would be much appreciated.


  • Moderators

    @QT_fan

    void setPBText ( const QString & txt, QPushButton * pb)
    {
          pb->setText ( txt );
    }
    

    Could be used as in

    setPBText ( "ON", ui->MyButton_1 );
    

    Please check it out



  • Thanks for your response. I tried it and got this error message:

    C:\Qt\Apps\Practice_4\mainwindow.cpp:32: error: undefined reference to `MainWindow::setPBText(QString const&, QPushButton*)'


  • Lifetime Qt Champion

    Hi,

    Did you add that function to your QMainWindow subclass ?



  • I placed the function in the mainWindow file with a prototype in the header file. I did this since this is where Qt designer put the button slot function. Wrong place? Anyway, I moved it to the header file and it now works! Once again, thank you for your assistance.


  • Moderators

    @QT_fan

    The short routine I have suggested is a plain function. In a header would need to have something like

    #ifndef SET_PB_TEXT_INCLUDED 
    #define SET_PB_TEXT_INCLUDED  
    
    #include <QString>
    #include <QPushButton>
    
    void setPBText ( const QString & txt, QPushButton * pb);
    #endif 
    

    Certainly you can also include it also in a header file and in a class definition as you have done. However, you would have to add the scope of the class when adding the source somewhere. In your case the source snippet would be more like:

    void MainWindow::setPBText ( const QString & txt, QPushButton * pb)
    {
          pb->setText ( txt );
    }
    

    No offence, but I suggest that you have also a look to some C++ basics. Without knowing some C/C++ basics you are making your life harder than it needs to be with Qt.

    PS: all source is brain to keyboard and requires some testing and checking.


Log in to reply
 

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