so this is my problem : I would like to handle a clicked link in a QWebView. There is the signal
void QWebView::linkClicked ( const QUrl & url )
that is emitted when the user clicks on a link, so I could use that for my purposes, but it depends of the value of linkDelegationPolicy property that is set by default to not delegate links
but I can't change this because it's a function of QWebPage and I have a QWebView and QWebView doesn't inherit from QWebPage...so I'm really confused
Any help please! Thanks!
The QWebView has an underlying QWepPage. You can get a pointer to it using the method QWebView::page().
Related
I have been reading though a couple of examples and post but I just cannot figure out how to add a shortcut to my custom context menu. My GUI has several elements. One of them is a treeView. For the elements in my treeView I would like to have a custom context menu.
My first approach was according to this tutorial here. The context menu itself worked but the shortcuts cannot work if you create the actin within the show function.
So my second approach was according to this tutorial. But still my shortcuts do not work and if I use the context menu all actions are called twice...
Since I did not find a tutorial or code example, which matches my case, I hope that someone here can explain to me how this is correctly done in theory. Adding a shortcut to an action for a custom context menu.
Where do I have to declare my action?
What needs to be the parent of the action?
On which widget do I need to call addAction?
Thanks for any hints.
Another way is to add your action also to the parent widget (or main window widget). As mentioned in this reply, adding the same action to multiple widgets is fine and it's the way QActions are supposed to be used.
Example with custom HtmlBrowser class deriving from QTextBrowser:
Ctrl+U shortcut works for this code:
HtmlBrowser::HtmlBrowser(QWidget * parent) : QTextBrowser(parent)
{
viewSourceAct = new QAction(tr("View/hide HTML so&urce"), this);
viewSourceAct->setShortcut(tr("Ctrl+U"));
viewSourceAct->setCheckable(true);
parent->addAction(viewSourceAct);
connect(viewSourceAct, &QAction::triggered, this, &HtmlBrowser::viewSourceToggle);
}
and Ctrl+U shortcut does not work with this code (same as above, but without parent->AddAction(...)):
HtmlBrowser::HtmlBrowser(QWidget * parent) : QTextBrowser(parent)
{
viewSourceAct = new QAction(tr("View/hide HTML so&urce"), this);
viewSourceAct->setShortcut(tr("Ctrl+U"));
viewSourceAct->setCheckable(true);
connect(viewSourceAct, &QAction::triggered, this, &HtmlBrowser::viewSourceToggle);
}
Curiously, parent in this case is another widget (tab widget), not MainWindow. Still, adding parent->addAction() helps. And, unlike your suggested answer, it works even when connecting action to simple methods, without slots. Works for me in Qt 5.15.0. Not quite sure why it works, though. Perhaps, the widget the action is added to must be permanent for shortcuts to work? Looks like a bug in Qt.
Thanks to Scheff's hint I got it working. I do not now if this is really the correct way but this works for me.
The action needs to be declared in the constructor of your GUI class (e.g. MainWindow):
actionDel = new QAction(tr("delete"), this);
actionDel->setShortcut(QKeySequence(Qt::Key_Delete));
connect(actionDel, SIGNAL(triggered()), this, SLOT(actionDel_triggered()));
The triggered signal needs to be connected to a slot. Hint: if you create the slot do not use on_ACTIONNAME_triggered, this will interfere with the designer and cause a connection error.
Next add the action to a custom menu
fileContextMenu = new QMenu(this);
fileContextMenu->addAction(actionDel);
And to the widget
ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->treeView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showDirContextMenu(QPoint)));
ui->treeView->addAction(actionDel);
All in the constructor of your GUI class.
To show the context menu use the following code in slot used in the above connect:
QModelIndex index=ui->treeView->indexAt(pos);
// Here you can modify the menu e.g. disabling certain actions
QAction* selectedItem = fileContextMenu->exec(ui->treeView->viewport()->mapToGlobal(pos));
If you do not have a slot for an action, the action can be also handled in the context menu slot, but this does not work with shortcuts!
if(selectedItem == actionOpen){
on_treeView_doubleClicked(index);
}
I Use WebEngineView QML Type to show a web page that have some link that need to open in a new tab. Links are somethings like
Go to google in new tab
I want to open the URL of newViewRequested signal in an external browser but the WebEngineNewViewRequest has no 'url' property that I can use with Qt.openUrlExternally(request.url).
WebEngineNewViewRequest has a private member QUrl m_requestedUrl that not accesible as property in qml.
How can I handle the issue,get the URL and open it in an external browser.
Thanks.
In Qt5, you can use navigationRequested signal to achieve this:
onNavigationRequested: function(request) {
if (request.navigationType === WebEngineNavigationRequest.LinkClickedNavigation) {
Qt.openUrlExternally(request.url)
}
request.action = WebEngineNavigationRequest.IgnoreRequest
}
The line of assigning IgnoreRequest to the action property is to make sure the URL is not opened in the WebEngineView.
I am using a QWebView in this way:
QWebView *window = new QWebView();
window->setUrl(QString("my url"));
window->show();
And it works. I can see the html page I want.
The problem is this. By default if I "right click" on a link the action "Open in new window" is shown but if I click on it, nothing happens. If I "left click" on the same link it works.
So the problem is that no new windows are open by QWebView. Does anyone know why?
I have another problem. Some links are pdf file so I expect that QWebView ask me to download it or to run an application to open it. But nothing happens instead. I think the problem is related to the fact that no new windows are allowed to be opened by QWebView and not on the pdf.
Obviously I tested the page with a web browser and everything work well, so the problem is in some settings of QWebView.
Does anyone know how to make QWebView open new windows when required?
Notes:
all links are local resources.
The html links use this syntax (and they works):
Some link
The link to pdfs use this syntax (nothing happens when I click):
Some pdf
Try to handle cicks by yourself. Here is an example that can guide you. I have not compiled it though .
QWebView *window = new QWebView();
window->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);//Handle link clicks by yourself
window->page()->setContextMenuPolicy(Qt::NoContextMenu); //No context menu is allowed if you don't need it
connect( window, SIGNAL( linkClicked( QUrl ) ),
this, SLOT( linkClickedSlot( QUrl ) ) );
window->setUrl(QString("my url"));
window->show();
//This slot handles all clicks
void MyWindow::linkClickedSlot( QUrl url )
{
if (url.ishtml()//isHtml does not exist actually you need to write something like it by yourself
window->load (url);
else//non html (pdf) pages will be opened with default application
QDesktopServices::openUrl( url );
}
Note that if the HTML you are displaying may containing relative/internal links to other parts of itself, then you should use QWebPage::DelegateExternalLinks instead of QWebPage::DelegateAllLinks.
The above answer is informative but might be overwhelmed for this question.
Connecting signals to QWebPage::action(OpenLinkInNewWindow) or overriding QWebPage::triggerAction should solve this problem.
My application consists of a WebView widget. A mouse click on the widget is not handled by the mousePressEvent() of my application, but by the WebView widget. So, I installed an event filter to receive the events. Now, I get notified of all events, except the mouseReleaseEvent for the right click (Everything works fine for left clicks and mousePressEvent for the right click is also getting registered). I guess it has got something to do with context events getting generated by right clicks (a pop-up menu gets generated). But since I am using a filter, the event should first be sent to me. The following is the code for the event filter
in Jambi, but I hope I can modify an answer given in Qt for Jambi.
public boolean eventFilter(QObject o,QEvent event)
{
if (event.type()==QEvent.Type.MouseButtonPress) // One can call the mousePressEvent() functions from here,which can do this work but speed
{
if (((QMouseEvent)event).button()==Qt.MouseButton.LeftButton)
{
mousebuttontype=1;
clickedorpressed=1;
}
else
if (((QMouseEvent)event).button()==Qt.MouseButton.RightButton)
{
mousebuttontype=2;
System.out.println("right");
}
t1=QTime.currentTime();
t1.start();
}
else
if (event.type()==QEvent.Type.MouseButtonRelease)
{
if (t1.elapsed()>900)
{
switch(mousebuttontype)
{
case 1: browser.back();
break;
case 2: browser.forward();
break;
}
}System.out.println("choda");
}
return false;
}
MY BASIC AIM IS GETTING THE TIME INTERVAL FOR WHICH THE RIGHT CLICK WAS PRESSED. ANY WORKAROUND ?
Some digging around certainly seems to suggest that there may be no right-mouse release event being generated if that is the trigger for a context menu on your particular system. These are conveyed as a QContextMenuEvent.
This Qt Labs post hints about this too.
A work around may be tricky if it is system dependent. Have you tried overriding event() in the QApplication class to see if the event comes through there? Some events don't necessarily get to the children but everything goes through QApplication::event().
Another option for you is, subclass Qwebview and override mouseReleaseEvent event
I've found a fix for this that I dont think will be system dependent.
My particular case was using mouseReleaseEvent in order to catch the events, and use them myself. I didn't get these events.
On all child widgets of the widget that I want to handle the event, I added to the class definition:
protected:
void mouseReleaseEvent(QMouseEvent *event) {event->ignore();}
This overrides the default implementation for context menu's, and sends the mouseReleaseEvent back up the parent chain like it would for other mousebuttons.
http://doc.qt.io/qt-5/qevent.html#ignore
This shows that it will probably propagate to the parent widget. As the link indicates, this fixed it for me at Qt 5.9, but I think it should work for virtually all version.
(I am aware this question is literally 7 years old, but it doesn't contain the fix that I think would be the best fix, and shows up as result 2 on google(qt not getting mouse release event on rightclick). So I think it deserves an up to date answer.)
Without going in to broader implementation explanations, the core problem I needed to solve related to this issue was that I needed to know if a context menu swallowed the right-click so I could ensure some custom state was handled properly. The simplest workaround I was able to find was to implement contextMenuEvent, which gets called after mousePressEvent, to detect if the event was accepted (a context menu was opened somewhere in my QGraphicsScene/Items). Here is a minimal example in Python to demonstrate how the event state might be used:
def contextMenuEvent(self, event):
event.setAccepted(False)
super(MyGraphicsView, self).contextMenuEvent(event)
self.__context_menu_used = event.isAccepted()
Note you can also skip running the the base class contextMenuEvent entirely to block the scene/items from opening a context menu. This is handy if you want to do 3D-DCC-like alt-RMB-zooming without accidentally opening a context menu, e.g.:
def contextMenuEvent(self, event):
# Block context menus if alt is held down
if event.modifiers() & QtCore.Qt.AltModifier:
return
event.setAccepted(False)
super(MyGraphicsView, self).contextMenuEvent(event)
self.__context_menu_used = event.isAccepted()
I want to show the user a warning QMessageBox with a link inside. This is relatively easy, I just need to make sure I set the RichText text format on the message box and the QMessageBox setup does the rest. However, I would also like to close the message box (as in some-sort-of-call-to done()) if the user clicks on the link - the semantic being that the user acknowledged the message and made a decision.
The problem: QMessageBox hides the linkActivated signal coming from its inner QLabel (which is used to store the text).
I thought I could extend the QMessageBox class and do this very ugly hack in the constructor:
QLabel *lbl = findChild<QLabel*>(QString("qt_msgbox_label"));
assert(lbl != NULL);
connect(lbl, SIGNAL(linkActivated(const QString&)), this, SLOT(handle_link_activation(const QString&)));
but although the label found with findChild is not null, and the "qt_msgbox_label" is definitely correct (c/p'ed from the source), and there is no "no such signal/slot" message, my slot never gets called when I click the link.
I'd like to avoid writing my own QDialog which would mimic the QMessageBox behavior. Does anyone have any idea on how I can catch that signal?
Try defining your own link "protocol" i.e. msgboxurl://yoururl.is.here and install url handler for it
QDesktopServices::setUrlHandler("msgboxurl", urlHandlerObj, "slotName");
urlHandlerObj may be object that created message box. In slot you can just hide your message box and take url part after // and open it with QDesktopServices::openUrl but remember that you have to prepend then http/https prefix (on some platforms url without "scheme" is not handled properly). Slot handling url must have same parameters as QDesktopServices::openUrl static method