1

I'm pretty new to Qt and I'm trying to figure out how to pass a string to a MenuAction. I'm missing one small thing and I hope you can help.

I'm using the TabBrowser example at http://doc.qt.io/qt-5/qtwebkitexamples-webkitwidgets-browser-example.html and trying to add the option to "Copy Link Text" to the menu to copy the text contents of a right-clicked link to the clipboard. I can add the menu item and get the text, but I don't see how to pass it to the slot.

Here's the code I'm using. What's the puzzle piece that I'm missing?

void WebView::copyLinkText(QString& text)
{
    QClipboard* clip = QApplication::clipboard();
    clip->setText(text);
}

void WebView::contextMenuEvent(QContextMenuEvent *event)
{
    QWebHitTestResult r = page()->mainFrame()->hitTestContent(event->pos());
    if (!r.linkUrl().isEmpty()) {
        QMenu menu(this);
        menu.addAction(pageAction(QWebPage::OpenLinkInNewWindow));
        menu.addAction(tr("Open in New Tab"), this, SLOT(openLinkInNewTab()));
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        // Add link to bookmarks...
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::CopyLinkToClipboard));
        QString linkText = r.linkText();
        QAction* action = menu.addAction(tr("Copy Link Text"), this, SLOT(copyLinkText()));
        if (page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled))
            menu.addAction(pageAction(QWebPage::InspectElement));
        menu.exec(mapToGlobal(event->pos()));
        return;
    }
    QWebView::contextMenuEvent(event);
}
Jason Champion
  • 2,670
  • 4
  • 35
  • 55

1 Answers1

0

Similar questions have been raised and answered, e.g. Passing an argument to a slot and How to pass a value with a clicked signal from a Qt PushButton? Quite a few techniques are mentioned there. To me, the "nicest" one seems to be the c++11-way of using lambdas, adopted from one of the posts above:

QAction* action = menu.addAction (tr ("Copy Link Text"));
connect (action, &QAction::triggered, this, [this]{ copyLinkText (linkText); });

Does this work for you? I didn't try it out, and have very little experience with this lambda+capturing stuff...

Community
  • 1
  • 1
ThorngardSO
  • 1,191
  • 7
  • 7