So I currently have a list of video clips being displayed in a QListView and have created a custom Delegate to paint preview thumbnails for them using data from a QStandardItemModel.
Ultimately I want to be able to animate the thumbnails as you mouse over them so they play a preview of the clip (by showing only a couple frames). I want two versions of this. One that just plays, and another that shows frames based upon your mouse position (further towards the left is the beginning of the clip, and as you move towards the right, it scrubs through).
Right now I am trying to figure out how to implement the animation piece. Should I be using the Delegate to draw frames and be updating a custom frame data on my model that the Delegate will use to know what frames to draw with a reimplemented paint function (already have the framework of a paint function there)? Or will this be too resource intensive? And then what is the best way to do that? I looked into editor widgets, but those seem to be not seem to edit model data/update delegates in realtime and instead only upon finishing editing. Also I would like this to initialize on mouseover and that doesn't seem to be an option in the built-in edit triggers.
class AnimatedThumbDelegate(QItemDelegate):
def __init__(self,parent=None):
super().__init__(parent)
self.height=200
self.width=self.height*1.77
self.frames=10
def paint(self,painter,option,index):
painter.save()
image=index.data(FootageItem.FILMSTRIP)
if not image.isNull():
painter.drawPixmap(QRect(option.rect),image,QRect(image.width()/self.frames*index.data(FootageItem.FRAME),0,image.width()/self.frames,image.height()))
painter.restore()
def sizeHint(self,option,index):
return QSize(self.width,self.height)
This delegate paints a portion of a strip image that I am using for preview frames and does so by referencing framedata. FootageItem is just a QStandardItem class that helps construct the data I want to store for these clips and I am just using indices from it here. It fetches a QPixmap from my model. The filmstrip image I am using looks like this:
Can I use an editor widget to update values and force a repaint on the delegate object based upon mouseMoveEvents? And then can I make editors appear on mouseovers? Or should I look at reimplementing QListView to update the delegate with mouse events? Or is there another way I haven't discovered?
I made a widget that behaves roughly how I would want the updating frames portion of this to work, but was hoping to port it over to a delegate class instead of a QWidget so I could have it display data from a table and utilize the Model/View programming that QT has to offer.
class ScrollingThumbnail(QWidget):
def __init__(self,parent,image,rect):
super().__init__(parent)
self.image=image
self.paused=False
self.frame=5
self.frames=10
self.bar=False
self.vis=True
self.thumbRect=rect
self.setMouseTracking(True)
def leaveEvent(self):
self.stop()
def mouseMoveEvent(self,e):
if(e.pos().y()>self.height*0.6):
self.bar=True
self.pause()
self.frame=int(e.pos().x()/(self.width/self.frames))
self.repaint()
elif self.paused:
self.paused=False
self.bar=False
self.play()
def paintEvent(self,e):
qP=QPainter()
qP.begin(self)
if self.vis:
self.drawWidget(qP)
qP.end()
def drawWidget(self,qP):
if not self.image.isNull():
qP.drawPixmap(self.thumbRect,self.image,QRect(self.image.width()/self.frames*self.frame,0,self.image.width()/self.frames,self.image.height()))
if self.bar:
pen=QPen(QColor(255,255,255,50),self.height/60,cap=Qt.RoundCap)
qP.setPen(pen)
off=self.height/20
inc=((self.width-(off*2))/(self.frames-1))
qP.drawLine(off,self.height-off-20,off+(inc)*(self.frame),self.height-off-20)
def play(self):
if not self.paused:
self.frame=(self.frame+1)%self.frames
self.repaint()
self.timer=threading.Timer(0.1,self.play)
self.timer.start()
def pause(self):
try:
self.timer.cancel()
except:
pass
self.paused=True
def stop(self):
try:
self.timer.cancel()
except:
pass
self.frame=5
self.repaint()
It uses a threading timer as a cheap hacked way of playing frames in a loop. Probably will look more into better ways to achieve this (possibly using QThread?) Also a gif of it in action as far as desired behavior: i.imgur.com/aKoKs3m.gifv
Cheers,
Alex
Think I figured out a way to go about it using some signals and connecting some slots. Here are the proof of concept classes.
Created this editor class that will update the frame data via signal based upon the mouse position, and then will destroy the editor when your cursor leaves the widget/item. It doesn't really need a paintevent, but I just put one in there so I could see when editing was active.
class TestEditor(QWidget):
editingFinished = Signal()
updateFrame = Signal()
def __init__(self,parent):
super().__init__(parent)
self.setMouseTracking(True)
self.frame=5
def mouseMoveEvent(self,e):
currentFrame=int(e.pos().x()/(self.width()/10))
if self.frame!=currentFrame:
self.frame=currentFrame
self.updateFrame.emit()
def leaveEvent(self,e):
self.frame=5
self.updateFrame.emit()
self.editingFinished.emit()
def paintEvent(self,e):
painter=QPainter()
painter.begin(self)
painter.setBrush(QColor(255,0,0,100))
painter.drawRect(self.rect())
painter.end()
My Delegate connects the editor signals to some basic functions. One will close the editor and the other will update the Frame Data on my model.
class TestDelegate(QItemDelegate):
def __init__(self,parent):
super().__init__(parent)
self.height=200
self.width=300
def createEditor(self,parent,option,index):
editor=TestEditor(parent)
editor.editingFinished.connect(self.commitEditor)
editor.updateFrame.connect(self.updateFrames)
return editor
def setModelData(self, editor, model, index):
model.setData(index,editor.frame,TestData.FRAME)
def paint(self,painter,option,index):
painter.save()
painter.setBrush(QColor(0,255,0))
painter.drawRect(option.rect)
painter.setPen(QColor(255,255,255))
painter.setFont(QFont('Ariel',20,QFont.Bold))
painter.drawText(option.rect,Qt.AlignCenter,str(index.data(TestData.FRAME)))
painter.restore()
def sizeHint(self,option,index):
return QSize(self.width,self.height)
def commitEditor(self):
editor = self.sender()
self.closeEditor.emit(editor)
def updateFrames(self):
editor=self.sender()
self.commitData.emit(editor)
Then all I had to do is enable mouse tracking and connect the "entered" signal to the "edit()" slot on my viewer
dataView=QListView()
dataView.setViewMode(1)
dataView.setMovement(0)
dataView.setMouseTracking(True)
dataView.entered.connect(dataView.edit)
Also had a super simple class for constructing test data items. Basically just set an empty Role to 5 for frame data.
class TestData(QStandardItem):
FRAME=15
def __init__(self,data=None):
super().__init__(data)
self.setData(5,self.FRAME)
It currently isn't fully functional as far as including a "play" function that will scrub through frames automatically. But I think that should be easy enough to set up. Also need to figure out how to now handle selections because the editor becomes active when you move over an item effectively blocking it from being selected. Currently looking into maybe implementing a Mouse up event that will then update the selection model attached to my viewer.
Related
Is there a way to lock docks in pyqtgraph so that the user cannot move them around?
I'm using a small touchscreen to display a pyqtgraph application with multiple docks. It is very easy for the user to accidentally move a dock. When that happens the screen becomes unusable because of the size. I would like to prevent the user from moving the docks.
However, the user must still be able to choose between docks (i.e. treat them like a tab widget).
Just to be clear, I want to prevent a dock from being detached and I want to prevent the dock from being drug to a new location.
Thanks,
Chris
I managed to disable the ability to detach and drag docks by overriding the Dock class' methods.
Dragging a dock moves it to another location. So I overrode all of the 'drag' event handlers with methods that do nothing (i.e. a no-op).
Double-clicking on a dock's label will cause the dock to detach. So, I overrode the dock's label's double-click event handler with a no-op.
Replace Dock with MyDock in your code. UPDATE: I added code to override the drag methods for the DockArea too because I was still able to move DockAreas around.
Here is the code:
##
# This class is used to eliminate a standard Dock class' ability to detach and
# move (i.e. dragging this Dock will have no effect)
#
class MyDock(Dock):
def __init__(self, name, area=None, size=(10, 10), widget=None, hideTitle=False, autoOrientation=True):
# Initialize the baseclass
#
Dock.__init__(self, name, area, size, widget, hideTitle, autoOrientation)
# Override the label's double click event. Normally double clicking
# the dock's label will cause it to detach into it's own window.
#
self.label.mouseDoubleClickEvent=self.noopEvent
def dragEventEnter(self, ev):
pass
def dragMoveEvent(self, ev):
pass
def dragLeaveEvent(self, ev):
pass
def dragDropEvent(self, ev):
pass
def noopEvent(self,ev):
pass
class MyDockArea(DockArea):
def dragEventEnter(self, ev):
pass
def dragMoveEvent(self, ev):
pass
def dragLeaveEvent(self, ev):
pass
def dragDropEvent(self, ev):
pas
I have a UI in which it consists of a few QPushButton and a QLineEdit and currently I am having trouble to 'update' the contents within this QMenu that was attached onto a QPushButton.
So assumingly, if there are already 2 cameras in my scene, and as I execute my UI, by pressing onto this setCameraBtn I will get the 2 cameras in the list. However, if I create a new camera where the UI is not yet close, how do I make my QMenu to read in the new camera, like a 'live-update'?
I tried creating another function where it re-read the cameras in scene and retabulate the camLs as well as a connection similar to the one that I have written in the createConnections but it does not seems to be reading in.
camLs = []
class orientCameraUI(QDialog):
def __init__(self, parent=None):
...
...
def initUI(self):
...
...
def createConnections(self):
self.connect(self.orientToCamBtn, SIGNAL('clicked()'), self.orientToCam)
def camMenu(self):
allCams = [cam for cam in cmds.listRelatives(cmds.ls(cameras=1),parent=1) if cam not in ['front','persp','side','top']]
camLs.extend(allCams)
menu = QMenu("menu", self.setCameraBtn)
for item in camLs:
menu.addAction(QAction(item, menu))
self.setCameraBtn.setMenu(menu)
menu.triggered.connect(self._camSelected)
def _camSelected(self, action):
self.currentCamTxt.setText(action.text())
This can be easily accomplished by firing a QThread instead the UI that periodically call a update camera method which checks for the current cameras in the scene and compares them with the one that the UI has already registered. And if there is an addition, change or deletion in the camera(s) then it updates the menu to reflect it.
Another solution is to use scriptJob.
I have created a ui from scratch using the commands within Maya documentation.
The following function that I have wrote applies in two scenerios:
When the user has clicked onto another button - Import, in which it will do as what it was written in the code then close it off with the following function (see readFile function)
When user has clicked onto the button where it close the UI without running anything.
In my script, to cater the above two scenarios, I wrote as the following where closeWindow is catered to Scenario1 and cancelWindow is catered to Scenario2
def ui(self):
...
cancelButton = cmds.button( label='Cancel', command=self.cancelWindow, width=150, height=35)
def closeWindow(self, *args):
cmds.deleteUI(self.window, window=True)
def cancelWindow(self, *args):
cmds.delete(camSel[0])
cmds.deleteUI(self.window, window=True)
def readFile(self, *args):
...
self.closeWindow()
As such, is it possible to create some sort of signal like those in PyQt (clicked(), returnPressed() etc) by combining the above 2 (automated + manual), seeing that the deleteUI command usage is the same?
Default Maya UI provides only callbacks, not signals. You can create a sort of 'pseudo signal' by calling an event handler object instead of a function. In that scenario the button only knows 'I fired the button event' and the handler can call as many functions as needed.
class Handler(object):
def __init__(self):
self.handlers = []
def add_handler (self, func):
self.handlers.append(func)
def __call__(self, *args, **kwargs):
for eachfunc in handler:
eachfunc(*args, **kwargs)
hndl = Handler()
hndl.add_handler(function1) # do some ui work...
hndl.add_handler(function2) # do some scene work...
hndl.add_handler(function3) # do something over network, etc....
b = cmds.button('twoFunctions', c = Hndl)
In a large complex UI this is a nice way to keep minor things like button higlights and focus changes separated out from important stuff like changing the scene. In your application it's almost certainly overkill. You've only sharing 1 line between close and cancel, that's not too bad :)
Heres' more background on on pseudo-events in maya gui.
You can also use Maya's QT directly to get at the close event... Again, seems like overkill. More here
I have done a fair amount of searching for this problem, which is probably trivial. However I am new to pyQT and am completely stuck. Any help would be appreciated.
I simply want to place, move and draw objects on a QGraphicsView widget using QGraphicsScene.
The following code to handle mouse press events works, but it fires when the mouse is clicked anywhere in the form and not just in the QGraphicViewer (also as the result of this the object is subsequently placed in the wrong place).
Here is an extract from the code I'm using now
def mousePressEvent(self, ev): #QGraphicsSceneMouseEvent
if ev.button()==Qt.LeftButton:
item = QGraphicsTextItem("CLICK")
item.setPos(ev.x(), ev.y())
#item.setPos(ev.scenePos())
self.scene.addItem(item)
I know I should be using the QGraphicsSceneMouseEvent and I can see how this is implemented in C++; but I have no idea how to get this to work in Python.
Thanks
Try extending QtGui.QGraphicsScene and using its mousePressEvent and the coordinates from scenePos(). Something like:
class QScene(QtGui.QGraphicsScene):
def __init__(self, *args, **kwds):
QtGui.QGraphicsScene.__init__(self, *args, **kwds)
def mousePressEvent(self, ev):
if ev.button() == QtCore.Qt.LeftButton:
item = QtGui.QGraphicsTextItem("CLICK")
item.setPos(ev.scenePos())
self.addItem(item)
Can anybody recommend how to switch between scenes in pyglet.
I.e.
menu > game
game > menu
menu > help
ect
The only way that i can think to do it off the top of my head is by using different windows, which i am quite sure would be the complete wrong way to do it. Or by overloading all of the window's event functions.
Sorry if i haven't made myself clear but any help would be appreciated
The cocos2d.org framework is built on pyglet and includes scene management.
Here is a rough schematic of a class structure that might work for you:
class Game(object):
"This class contains the Scene which is the current scene the user is look ing at."
def __init__(self):
self.current_level = 0
self.current_screen = MainMenu(self)
def load(self):
"Load progress from disk"
pass
def save(self):
"Save progress to disk"
pass
def clearCurrentScreen(self):
self.current_screen.clear()
self.window.remove_handlers()
def startCurrentScreen(self):
self.window.set_handler("on_key_press", self.current_screen.on_key_press)
# etc
self.current_screen.start()
def gotoNextLevel(self):
"called from within LevelPlayer when the player beats the level"
self.clearCurrentScreen()
self.current_level += 1
self.current_screen = LevelPlayer(self, game, self.current_level)
self.startCurrentScreen()
def startPlaying(self):
"called by the main menu when the user selects an option"
self.clearCurrentScreen()
self.current_screen = LevelPlayer(self, game, self.current_level)
self.startCurrentScreen()
def execute(self):
self.window = pyglet.window.Window()
self.startCurrentScene()
pyglet.app.run()
class Screen(object):
def __init__(self):
pass
def start():
pass
def clear():
"delete all graphical objects on screen, batches, groups, etc. Clear all state in pyglet."
pass
def on_key_press(self, key, etc):
pass
def on_draw(self):
pass
# etc
class LevelPlayer(Screen):
"This class contains all your game logic. This is the class that enables the user to play through a level."
def __init__(self, game, level_to_play):
pass
# be sure to implement methods from Screen
class MainMenu(Screen):
"This class presents the title screen and options for new game or continue."
def __init__(self, game):
self.game = game
def handleNewGame(self):
self.game.startPlaying()
def handleContinue(self):
self.game.load()
self.game.startPlaying()
# be sure to implement methods from Screen
game = Game()
game.execute()
So you have a Game class who owns the window and that manages which Screen is displayed to the user. Here I use "Screen" to mean what the user is interacting with, for example a MainMenu, or a LevelPlayer. The key here is the clear() method of Screen, which you should implement to delete all the sprites, media, groups, and batches that you were displaying. You also have to remove the window handlers on clear and set them on start.
You can see this solution in action here: https://github.com/superjoe30/lemming/tree/master/lemming
I'm not very experienced, but for what it's worth, the method I use is as follows. It does not recognise explicit 'states' or 'scenes' as such, but rather it relies on the adding (and removal) of discrete items into my game world. Each such item may have its own key handlers, and knows how and when to create other such items.
A specific example:
GameItem is a subclass for all items that can be put into the world. It is a simple collection of attributes, with no behaviour. It is subclassed by items in the game world like Bush, Player, etc, and also by HUD items like ScoreDisplay and MainMenu.
World is just a collection of GameItems.
My 'update' function iterates through all items in the world, calling their update method if they have one.
My 'draw' function similarly iterates through all items in the world, drawing each of them. (many of them might be drawn en-masse by simply calling something like pyglet's Batch.draw)
Right at application start-up, one of the first items I add to the world is a MainMenu object. It has an on_key_down method.
World.add looks at the item being added. If an item has an on_key_down method, then it adds this handler to the pyglet key handlers stack. (Similarly, it undoes this in World.remove) (Actually, on reflection, I guess world.add raises an event when it adds an item. If the application's keyboard handler module is interested, then on recieving one of these events it then does the adding of the item's key hander, but this is kinda incidental to the question)
The MainMenu.on_key_handler method looks at the pressed key, and if it's the key to start the game, then it makes a series of calls:
# Do everything needed to start the game
# For dramatic pacing, any of these might be scheduled to be
# called in a second or so, using pyglet.clock.schedule_once
world.add(player)
camera.to_follow(player)
world.add(scoredisplay)
# Finally, remove the main menu from the world
# This will stop showing it on screen
# and it will remove its keyboard event handler
world.remove_item(self)
This is just a simple example, but hopefully you can see how, instead of starting the game, the mainmenu could instead display secondary menus by adding them to the world, or any such thing.
Once in the game, you can change 'scenes' by simply calling 'world.remove' on all items that you no longer want visible, and calling 'world.add' on all the items in the new scene.
An example of a game that uses this technique is previous pyweek entry SinisterDucks:
http://code.google.com/p/brokenspell/
(although, to be fair, it does not feature distinct 'scenes' during gameplay. It merely usesthis technique to manage menus, game over screen, etc)
The solution i ended up using is by giving the main window a stack and having it pass all events out to items on the top of the stack.
i.e.
class GameWindow(pyglet.window.Window):
def __init__(self,*args, **kwargs):
pyglet.window.Window.__init__(self, *args, **kwargs)
self.states = [PlayLevel(self)] ## Starting State
def on_draw(self):
if hasattr(self.states[-1],"on_draw"):
self.states[-1].on_draw()
def on_mouse_press(self,*args):
if hasattr(self.states[-1],"on_mouse_press"):
self.states[-1].on_mouse_press(*args)
ect. For all of the other events that i use
i am currently in the process of writing up some functions to go in GameWindow that will manage pushing and popping scenes from the stack