PySide2/Python 2.7 : Having a QGraphicsItem receiving a keyPressEvent - python

I am having trouble with passing a keyPressEvent in my custom QGraphicsItem, and I am not sure if I understand well how it works on this kind of objects. I know it has been asked already and I have found a lot of similar questions in C++ and a few in Python, but I could not make it work in my script...
In Qt's documentation it is said:
Note that key events are only received for items that set the ItemIsFocusable flag,
and that have keyboard input focus.
My guess is that something is wrong in my code related to this sentence.
Basically, my class looks like that:
class myItem(QtWidgets.QGraphicsItem):
def __init__(self, **kwargs):
super(myItem, self).__init__(**kwargs)
self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable)
self.setFlag(QtWidgets.QGraphicsItem.ItemIsFocusable)
def keyPressEvent(self, event):
if event == QtCore.Qt.Key_Delete:
self.scene().removeItem(self)
return super(myItem, self).keyPressEvent(event)
Am I missing a flag, or do I need to set up something in my scene class, or something like that?
Cheers :)

Related

Keeping classes loosely coupled and sharing data

I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.
Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?
As an example
class Window():
def __init__(self, parent=None):
self.parent = parent
def doStuff(self):
#do work here
class ParseMyWork(Window):
def __init__(self, parent=None):
self.parent=parent
I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork
There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.
Any answers to the question don't necessarily have to be in python, but it will be helpful if they are
If I'm understanding your question correctly, I would say that inheritance is not necessary in your case. Why not give ParseMyWork a function for dealing with a specific Window task?
class Window():
def __init__(self, parent=None):
self.parent = parent
def doStuff(self):
#do work here
class ParseMyWork():
def __init__(self, parent=None):
self.parent=parent`
def doWindowActivity(self, window):
window.doStuff
Then you can use the function like this
work_parser = ParseMyWork()
window = Window()
work_parser.doWindowActivity(window);
That way you can use your work_parse instance with any window instance.
Apologies in advance for my Python, it's been a while so if you see any rookie mistakes, do point them out.
Keep it simple.py:
def doStuff(window):
#do work here
return window
def parseStuff(stuff):
pass
really.py:
from simple import doStuff, parseStuff
def really_simple(window):
okay = doStuff(window)
return parseStuff(okay)
don't complicate the class:
from really import really_simple
really_simple(window)
imo: classes are overly complicated objects, and in a lot of cases more confusing than they need to be, plus they hold references and modify stuff, and can be difficult to decouple once they have been tied to other classes. if there isn't a clear reason why a class needs to be used, then it probably doesn't need to be used.
Classes are super powerful, so it's good you're getting started with em.
Discalimer: Haven't worked in python for a while now, so things might not be exact. The general idea still applies though.
Getting into your question now:
I would say the best way to achieve what you want is to create an instance of the first object where you will extract information from.
Now when creating a class, it's vital that you have attributes within them that you will want to be stored within it that you would like to retrieve once the class is instantiated.
For example, using your Window class example above, let's say that you have an attribute called resolution. It would look something like this:
class Window():
def __init__(self, parent = None):
self.parent = None
self.resolution = '40x80'
Now the resolution information associated with your Window class is forever part of any Window class instance. Now, the next step would be to create a get method for resolution. This should be done as follow:
class Window():
def __init__(self, parent = None):
self.parent = None
self.resolution = '40x80'
def getResoultion():
return self.resolution
Now, the reason we created this get method is because we can now set a variable to the information that is returned with it.
So let's say that you have everything associated with your Window class in its own file (let's say the file name is called Window.py). In a separate file (let's call it main.py), you can do the following:
import Window
windowInstance = Window()
windowResolution = windowInstance.getResolution()
If you print out the variable windowResolution, you should get that 40x80 printed out.
Now, as a side note, I do believe it is possible to get the information associated with an attribute with an instance of a class by simply doing something like
windowResolution = windowInstance.resolution
but that is bad practice in general. The reason, in a nutshell, is because you are now exposing attribute names of your class which you do not want to do because it makes it easy for a person outside of your code to learn the name where that information is held and change it. This can then lead to a myriad of other problems when it comes to making an overall program work. That is why it is best practice to use getters and setters. I already showed what getters are. Simply a get method for attributes. Setters, as you can probably assume, allow for one to set the information of an attribute to something else. Now you might say "Gabe, if we can create setter methods, what's the point of it if they just change it". My answer to that is to not give a setter method to all attributes. For attributes you don't mind for a person to change, give it a setter method, but for attributes you do not want any outside users to touch, simply don't create a setter method for it. Same goes with getter methods too. Users don't need to see all of the information of all attributes that makes your program work. Here's a better explanation: https://en.wikipedia.org/wiki/Mutator_method
Now, back to your example. Now let's say you have your ParseMyWork class in its own file like we did with your Window class, and let's say that ParseMyWork needs the resolution info from Window class. You can do the following :
import Window
import ParseMyWork
windowInstance = Window()
windowResolution = windowInstance.getResolution()
parseInstance = ParseMyWork(windowResolution)
This will only pass the window resolution information associated with your Window class. Hope this helps.

Drag and drop with pyqt5 (SIGNAL)

I am trying to get drag and drop (with images or files) working for my listwidget in pyqt5. I can find a lot of examples with pyqt4, but there is one part that does not work in the newer version:
In the "dropevent":
self.emit(QtCore.SIGNAL("dropped"), links)
and in the MainForm:
self.connect(self.view, QtCore.SIGNAL("dropped"), self.pictureDropped)
I read a lot of posts but can't seem to find an answer how this should be written down with pyqt5. Could anyone please help me with this?
link to the entire example:
PyQT4: Drag and drop files into QListWidget
Simple.
The signal must come first
The slot come as parameter.
You must connect only after the signal was created
You must emit only after the connection was made.
Here we go with a small example:
self.signalOwner.mySignal.connect(self.slotFunction)
In your example let's say and consider that the view owns the signal and that pictureDropped is your slot function, so:
self.view.dropped.connect(self.pictureDropped)
Remember, your signal must emit certain type(s) or nothing at all andddd your #pyqtSlot function must receive same type(s) with the function receiving the same amount of parameter that your signal emits.
I have made a post some short time ago about drag and drop with images, had many difficulties to figure it out how to accept events and how the classes behave, it's a bit deeper than only signals so, if you need here is the POST :D
Your linked example uses the old-style signal and slot syntax, whereas you need to use the new-style syntax. In PyQt4 (versions 4.5 or later), you could use either style, but PyQt5 only supports the new style.
The old-style syntax allowed custom signals to be emitted on-the-fly, but the new-style syntax demands that the signal is declared beforehand on the class:
class ListWidget(QtWidgets.QListWidget):
dropped = QtCore.pyqtSignal(list)
def __init__(self, parent=None):
...
def dropEvent(self, event):
...
self.dropped.emit(list_of_files)
The signal connection is then made like this:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
...
self.listWidget = ListWidget()
self.listWidget.dropped.connect(self.handleDropped)
def handleDropped(self, list_of_files):
print('dropped:', list_of_files)

About the super() function

I'm using QtDesign to create my own UI and convert it to python version. So after subclass the UI python file, i had written some function to implement mouseEvent for QGraphicsView. Just one small question. How can i call the super() function for the QGraphicsView?
class RigModuleUi(QtGui.QMainWindow,Ui_RiggingModuleUI):
def __init__(self,parent = None):
super(RigModuleUi,self).__init__(parent = parent)
self.GraphicsView.mousePressEvent = self.qView_mousePressEvent
def qView_mousePressEvent(self,event):
if event.button() == QtCore.Qt.LeftButton:
super(RigModuleUi,self).mousePressEvent(event)
Look like the super(RigModuleUi,self).mousePressEvent(event)will return the mouseEvent for QMainWindow, not QGraphicsView. So all other option for mouse like rubberBand will lost.
Thanks
I'm not quite sure what you expect to happen here. You're storing a bound method. When it's called, it'll still be called with the same self it had when you stored it.
Your super is walking up the ancestry of RigModuleUi, which doesn't inherit from QGraphicsView.
self.GraphicsView is a funny name for an instance attribute; is that supposed to be the name of a class, or is it just capitalized incidentally? (Please follow PEP8 naming conventions.) Perhaps you'd have more luck if you defined the method as a global function and assigned that to the instance.
def qView_mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
super(QGraphicsView, self).mousePressEvent(event)
class RigModuleUi(QtGui.QMainWindow, Ui_RiggingModuleUI):
def __init__(self, parent=None):
super(RigModuleUi,self).__init__(parent=parent)
self.GraphicsView.mousePressEvent = qView_mousePressEvent
Guessing wildly here; I don't know PyQt's class hierarchy :)

QStandardItemEditorCreator in PySide

I'm trying to implement Qt's Color Editor Factory Example (http://doc-snapshot.qt-project.org/4.8/itemviews-coloreditorfactory.html) in PySide.
The problem I'm facing is that QStandardItemEditorCreator class is not in PySide, or I haven't been able to find it after searching the docs for a long time. The only reference to it in the PySide documentation can be found in the following page (http://www.pyside.org/docs/pyside/PySide/QtGui/QItemEditorCreatorBase.html), the relevant part being the following:
QStandardItemEditorCreator is a convenience template class that can be used to register widgets without the need to subclass PySide.QtGui.QItemEditorCreatorBase .
Without any link to QStandardItemEditorCreator.
In short, how may I get QStandardItemEditorCreator's functionality in PySide?
Thanks.
I ended up implementing QStandardItemEditorCreator in python. Here's my implementation:
class QStandardItemEditorCreator(QItemEditorCreatorBase):
def __init__(self, cls):
super(QStandardItemEditorCreator, self).__init__()
self.propertyName = cls.staticMetaObject.userProperty().name()
self.cls = cls
def createWidget(self, parent):
return self.cls(parent)
def valuePropertyName(self):
return self.propertyName
If anyone has a better answer I'll gladly choose yours over mine.

QWheelEvent.ignore() not passing event through?

In a subclass of QGraphicsView, I implemented the wheelEvent(event) event-handler as follow:
def wheelEvent(self, event):
print "Wheel event received"
event.ignore()
From what I understand, this should actually do little more than printing the above string. The QWheelEvent.ignore() should pass the event to the parent and go about its usual business (namely scrolling). The documentation is explicit about this:
If you reimplement this handler, it is very important that you ignore() the event if you do not handle it, so that the widget's parent can interpret it.
In this case, the QGraphicsView is the main widget, so it has no parent (unless by parent one means the parent class from which it is derived).
In practice however, the string is printed as expected but the view does not scroll its content.
So how do I implement this method and get the QGraphicsView to scroll?
Well if you are never calling the main class, it will be pretty hard for the parent (and yes that's the object you are inheriting from) to do anything, when would the code run?
Adding super(type(self), self) should help (thanks to #mata for the correct python2 syntax)

Categories