Ericson Willians
Ericson Willians

Reputation: 7845

How to detect if a mouse button was pressed on a QWebView?

I'm developing a Web Browser with PyQt4 and here's the part of the code that creates QWebViews:

def compose_tab(self, index):
        self.tabs[index].append(QtWebKit.QWebView())
        self.tabs[index][0].setLayout(self.tabs[index][1])
        self.tabs[index][1].addWidget(self.tabs[index][2])
        self.tabs[index][2].connect(self.tabs[index][2], QtCore.SIGNAL("linkClicked(const QUrl&)"), self.update_link)
        self.tabs[index][2].load(QtCore.QUrl("http://www.google.com"))
        self.url_field.setText("http://www.google.com")

I want to detect when a mouse button is pressed on a QWebView.

Upvotes: 1

Views: 617

Answers (2)

Ericson Willians
Ericson Willians

Reputation: 7845

For future lost souls, here's how I did it:

class CQWebView(QtWebKit.QWebView): 

    def mousePressEvent(self, event):
        if type(event) == QtGui.QMouseEvent:
            if event.button() == QtCore.Qt.LeftButton:
                self.emit(QtCore.SIGNAL("FIRST_BUTTON_PRESSED"))
            elif event.button() == QtCore.Qt.MiddleButton:
                self.emit(QtCore.SIGNAL("MIDDLE_BUTTON_PRESSED"))
            elif event.button() == QtCore.Qt.RightButton:
                self.emit(QtCore.SIGNAL("RIGHT_BUTTON_PRESSED"))

Although I have to warn you, the "linkClicked(const QUrl&)" signal ceases to be emitted after you do this, so you'd need to emit it on your own (I've tested it, it's possible).

Upvotes: 0

mfitzp
mfitzp

Reputation: 15545

In the documentation for QWebView you can see that this class inherits from QWidget. This means that it should have access to all the event handlers found on the QWidget class.

These include mousePressEvent which is the most generic, and contextMenuEvent which specifically works for registering right-click events.

There is also a specific signal for handling custom context menus customContextMenuRequested which might be of interest.

Upvotes: 1

Related Questions