[SOLVED] Reusable function/slot to copy text from multiple buttons to the clipboard



  • Hi,

    I have 10 buttons where its text is constantly changing based on some calculations (I'm using a button instead of a QLabel). What I want is to be able to copy its own text to the clipboard when it is clicked.

    I have no problems doing this, I could add a slot to each button and add the following code to each one...

    @void MainWindow::on_buttonName_clicked()
    {
    QClipboard *clip = QApplication::clipboard();
    QString input = ui->buttonName->text();
    clip->setText(input);
    }@

    ... and everything should be fine but what I would like to be able to do is to reuse the same function/slot for all of them, in other words instead of creating 10 different slots I would like to be able to create just one and call it from each button, something like...

    @void MainWindow::reusableFunction()
    {
    QClipboard *clip = QApplication::clipboard();
    QString input = this->buttonName->text();
    clip->setText(input);
    }@

    Can some one give me an idea or point me to where I can find that informaiton?

    I hope it make sense what I want to accomplish here.

    Thanks


  • Lifetime Qt Champion

    Hi,

    You can use one slot and use qobject_cast and sender() to get the button, or use a QButtonGroup

    Hope it helps


  • Moderators

    i don't like the method, but it will help you in your situation.
    you can use the QObject::sender() :
    @
    void MainWindow::reusableFunction()
    {
    QPushButton* button = qobject_cast<QPushButton*>( sender() );
    if( button )
    {
    QClipboard *clip = QApplication::clipboard();
    clip->setText( button->text() );
    }
    }
    @
    But note that it actually breaks the object-orientated principle and only works when you connect to the slot with direct connection.

    Edit: and once again too late.. :)



  • Another solution could be to keep all buttons in a list or vector and use the index of the button in this list or vector with the "QSignalMapper":http://qt-project.org/doc/qt-4.8/qsignalmapper.html . Then you could use the index in the setMapping() function.

    But I would prefer raven-worx approach.



  • raven-worx's sample worked. Thanks a lot.

    You mentioned that you don't like this method, what is that you don't like about it?

    Thanks


  • Moderators

    [quote author="raven-worx" date="1383742018"]
    But note that it actually breaks the object-orientated principle and only works when you connect to the slot with direct connection.
    [/quote]

    it's an error-prone approach, but as you can see it does it's job. It's just my favor.



  • Ok, thanks a lot for your help.


Log in to reply
 

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