this example
helped me a lot in understanding of how does the events work.
But I have another problem. After an event when I want to call a function of a main class it seems like it was starting from Filter class and, unfortunately I'm not able to fetch the content from Designer-made file.
class Filter(QtCore.QObject):
def eventFilter(self, widget, event):
if event.type() == QtCore.QEvent.FocusOut:
print 'focus out'
print widget.objectName()
if widget.objectName() == 'edit_notes':
StartQT4().object_edit_notes('edit_notes')
return False
else:
return False
class StartQT4(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self._filter = Filter()
self.ui.edit_notes.installEventFilter(self._filter)
def object_edit_notes(self, w):
self.__init__()
something = self.ui.edit_notes.toPlainText()
something = unicode(something).encode('utf-8')
print something
return False
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
Attribute .something prints nothing. I tried to call identical function with the signal method button clicked() and it works fine.
Can you help me with this?
You don't need a separate class for the event-filter. Any object which inherits QObject or QWidget will do, which includes QMainWindow.
So move the event-filter into your StartQT4 class, like this:
class StartQT4(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# filter the events through self
self.ui.edit_notes.installEventFilter(self)
def object_edit_notes(self, w):
# this will convert a QString to a python unicode object
something = unicode(self.ui.edit_notes.toPlainText())
print something
def eventFilter(self, widget, event):
if (event.type() == QtCore.QEvent.FocusOut and
widget is self.ui.edit_notes):
print 'focus out'
self.object_edit_notes('edit_notes')
return False
return QMainWindow.eventFilter(self, widget, event)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
Related
I am trying to reduce the height of the App when the MainWindow gets out of focus, but with the code below nothing like that happens.
class MyApp(QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.installEventFilter(self)
time_frame_values = [i/30 for i in range(30)]
self.timeFrame = map(lambda x: x**0.5, time_frame_values)
def eventFilter(self, widget, event):
if event.type() == QEvent.FocusOut:
self.on_focus_out()
print("Focus Out!")
return False
def on_focus_out(self):
print("Focus Out!!")
for i in reversed(self.timeFrame):
self.move(QPoint(ScreenSizeObject.width()-self.width()-10, ScreenSizeObject.height()-self.original_height-(i*300)))
self.ui.textDisplay.resize(QSize(self.ui.textDisplay.width(), self.ui.textDisplay.height() + (i * 15)))
time.sleep(0.01)
Here self.on_focus_out() will do the transition effect.
EXPECTATION: When I click anywhere out of the mainwindow I want the self.on_focus_out() to run.
REALITY: No TRANSITION EFFECT takes place, not even the print('Focus Out!') prints a character.
Thanks for your effort!!
For the desired behavior you are looking for,
change the QEvent.FocusOut to QEvent.WindowDeactivate and the problem is Solved!
Rewriting the Correct Code,
class MyApp(QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.installEventFilter(self)
time_frame_values = [i/30 for i in range(30)]
self.timeFrame = map(lambda x: x**0.5, time_frame_values)
def eventFilter(self, widget, event):
if event.type() == QEvent.WindowDeactivate:
self.on_focus_out()
print("Focus Out!")
return False
def on_focus_out(self):
print("Focus Out!!")
for i in reversed(self.timeFrame):
self.move(QPoint(ScreenSizeObject.width()-self.width()-10, ScreenSizeObject.height()-self.original_height-(i*300)))
self.ui.textDisplay.resize(QSize(self.ui.textDisplay.width(), self.ui.textDisplay.height() + (i * 15)))
time.sleep(0.01)
How can I call and run a function with given number of inputs using mouseDoubleClickEvent of a GraphicsView which is in a QMainWindow?
My schematic code:
class MainWindow(QMainWindow):
...
def __setUI(self, appTitle="[default title]"):
...
self.graphicsView = GraphicsView(self)
self.graphicsView.mouseDoubleClickEvent = self.MyFunc(self.in_1, self.in_2)
def MyFunc(self, event, input_1, input_2):
...
I used this code, but is doesn't work. please help me to know how I can call
and run MyFunc using mouseDoubleClickEvent of graphicsView which is in MainWindow.
Many Thanks
One solution is to pass a lambda, something like:
self.graphicsView.mouseDoubleClickEvent = lambda event : self.MyFunc(self.in_1, self.in_2)
It works but it generates problems since mouseDoubleClickEvent has implementation that with the previous code is deleted. In this case the best solution is to use an eventFilter but to viewport since it receives the mouse event.
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.graphicsView = QtWidgets.QGraphicsView()
self.setCentralWidget(self.graphicsView)
self.graphicsView.viewport().installEventFilter(self)
self.in_1 = 10
self.in_2 = 20
def eventFilter(self, obj, event):
if obj is self.graphicsView.viewport():
if event.type() == QtCore.QEvent.MouseButtonDblClick:
self.func(event)
return super(MainWindow, self).eventFilter(obj, event)
def func(self, event):
print(event.pos(), self.in_1, self.in_2)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
How can I get the value returned from mousePressEvent of a widget and apply it to another widget?
Here's the widget with the mousePressEvent:
class Text(QTextEdit):
...
def mousePressEvent(self, event):
if event.button()==Qt.LeftButton:
return "test"
Now I want to use the string returned from the event and apply it to another widget:
class OtherWidget(QWidget):
...
self.label=QLabel()
self.label.setText(???) # <=== How to put the string here?
...
How can I do that? I have tried the following but it does not work.
self.label.setText(Text().mousePressEvent())
The events do not return anything for what you point out is impossible, Qt to send information asynchronously uses the signals, in the next part I show an example:
from PyQt5 import QtCore, QtWidgets
class Text(QtWidgets.QTextEdit):
mousePressSignal = QtCore.pyqtSignal(str)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
text = "test: {}-{}".format(event.pos().x(), event.pos().y())
self.mousePressSignal.emit(text)
class OtherWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(OtherWidget, self).__init__(parent)
self.label = QtWidgets.QLabel()
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.label, alignment=QtCore.Qt.AlignCenter)
#QtCore.pyqtSlot(str)
def setText(self, text):
self.label.setText(text)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
t = Text()
o = OtherWidget()
o.resize(640, 480)
t.mousePressSignal.connect(o.setText)
t.show()
o.show()
sys.exit(app.exec_())
I have a code that suppose to open/create new window if the link is target _blank but, it doesn't do as intended and gives no action in return.
Here is the code:
class MyPage(QWebEnginePage):
def __init__(self, parent=None):
super(MyPage, self).__init__(parent)
def triggerAction(self, action, checked=False):
if action == QWebEnginePage.OpenLinkInNewWindow:
self.createWindow(QWebEnginePage.WebBrowserWindow)
return super(MyPage, self).triggerAction(action, checked)
class MyWindow(QtWebEngineWidgets.QWebEngineView):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.myPage = MyPage(self)
self.setPage(self.myPage)
def createWindow(self, windowType):
if windowType == QWebEnginePage.WebBrowserWindow:
self.webView = MyWindow()
self.webView.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
return self.webView
return super(MyWindow, self).createWindow(windowType)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
main.load(QUrl("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target"))
sys.exit(app.exec_())
Would like to know why it's not working, if possible.
Thanks,
Max
If you directly test the link in any browser you will see that the action is to create a new tab, so windowType is for that case the type QWebEnginePage::WebBrowserTab, at that time we create the new window and show it as shown below:
class MyWindow(QWebEngineView):
[...]
def createWindow(self, windowType):
if windowType == QWebEnginePage.WebBrowserTab:
self.webView = MyWindow()
self.webView.setAttribute(Qt.WA_DeleteOnClose, True)
self.webView.show()
return self.webView
return super(MyWindow, self).createWindow(windowType)
I'm trying to catch a closeEvent for several dockWidgets that get added dynamically to a QMainWindow. It is unclear to me how I can figure out which widget has been closed.. Here's an simplified example:
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.leftDockWidget = QtGui.QDockWidget('pick tool', self)
self.leftDockWidget.setWidget( QtGui.QLabel('a dock widget') )
self.addDockWidget( QtCore.Qt.LeftDockWidgetArea, self.leftDockWidget )
self.leftDockWidget.closeEvent = self.dockWidgetCloseEvent
self.show()
def dockWidgetCloseEvent(self, event):
print event
# how to get sender widget ?
event.sender() doesn't seem to exist..
any ideas ?
thanks
One way to achieve what you want would be to use an event filter:
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.leftDockWidget = QtGui.QDockWidget('pick tool', self)
self.leftDockWidget.setWidget(QtGui.QLabel('a dock widget'))
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.leftDockWidget)
self.leftDockWidget.installEventFilter(self)
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.Close and
isinstance(source, QtGui.QDockWidget)):
print source.windowTitle()
return super(Example, self).eventFilter(source, event)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Example()
window.show()
sys.exit(app.exec_())
def dockWidgetCloseEvent(self, event):
self.sender()