gtk treeview: place image buttons on rows - python

For each row in my treeview, I want 4 image buttons next to each other. They will act like radio buttons, with only one being activateable at a time. Each button has an 'on' and 'off' image.
How do I do this? I figured out how to put images there, and how to put togglebuttons, but this seems to require some more effort as there is no pre-built cellrenderer that does what I want.
Basically what'd solve my problem is figuring out how to make an image in a gtk.treeview clickable. any ideas?

Have a look at this 'http://www.daa.com.au/pipermail/pygtk/2010-March/018355.html'. It shows you how to make a gtk.CellRendererPixbuf activatable, and able to connect to a click event signal.
cell = CellRendererPixbufXt()
cell.connect('clicked', func)
Update
As pointed out this answer, or the reference given doesn't work as advertised. It's missing the do_activate method, which needs to emit the clicked signal. Once it's done that, then the cell.connect will work.
Sorry if this answer mislead anyone.

Here is a short version without kiwi requirement.
class CellRendererClickablePixbuf(gtk.CellRendererPixbuf):
__gsignals__ = {'clicked': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
(gobject.TYPE_STRING,))
}
def __init__(self):
gtk.CellRendererPixbuf.__init__(self)
self.set_property('mode', gtk.CELL_RENDERER_MODE_ACTIVATABLE)
def do_activate(self, event, widget, path, background_area, cell_area,
flags):
self.emit('clicked', path)

Here is what worked for me:
class CellRendererClickablePixbuf(gtk.CellRendererPixbuf):
gsignal('clicked', str)
def __init__(self):
gtk.CellRendererPixbuf.__init__(self)
self.set_property('mode', gtk.CELL_RENDERER_MODE_ACTIVATABLE)
def do_activate(self, event, widget, path, background_area, cell_area, flags):
self.emit('clicked', path)

Related

Changing icon in nested menus

I don't think this may be posssible but I had still want to try asking.
In the attached screenshot, I have nested menus.
Is it possible to change the arrow keys icon as 'highlighted' by the red box?
I am trying to change the arrow key to a plus icon if there are no sub menu items found.
The default arrow can be in use if there are sub menu items found.
Yes, you can change the color of right-arrow.
But there is a trick to change it.
The truth of indicator is "branch-closed png file"
You can see the png file at the almost bottom on the page in the link.
So, it can not be solved by the pure-programmic way.
You prepare the picture in advance by yourself.
and please following code in QMenu constructor.
self.setStyleSheet("QMenu::right-arrow{image:url(stylesheet-branch-closed-red.png);}")
Attention:
stylesheet-branch-closed-red.png is my renamed picture.
You can download the original picture from the above link page.
you right-click the png picture and save as name.
This code comes from your past question.
class QCustomMenu(QtGui.QMenu):
"""Customized QMenu."""
def __init__(self, title, parent=None):
super(QCustomMenu, self).__init__(title=str(title), parent=parent)
self.setup_menu()
self.setStyleSheet("QMenu::right-arrow{image:url(stylesheet-branch-closed-red.png);}")
def setup_menu(self):
self.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
def contextMenuEvent(self, event):
no_right_click = [QAddAction]
if any([isinstance(self.actionAt(event.pos()), instance) for instance in no_right_click]):
return
pos = event.pos()
def addAction(self, action):
super(QCustomMenu, self).addAction(action)
As the result, it will become like this.
You will dislike the white part of the arrow.
No problem, you can delete them clearly with a free-paint soft, but I didn't do it because it was needless.

How to use QSignalMapper with QActions created dynamically?

I'd like to create a dynamic menu which enumerates all QDockWidget from my QMainWindow and allows to show/hide the QDockWidgets, so far I got this code:
class PluginActionsViewDocks():
def __init__(self, main_window):
self.main_window = main_window
mapper = QSignalMapper(self.main_window)
self.actions = []
for dock in main_window.findChildren(QtWidgets.QDockWidget):
action = create_action(
main_window, dock.windowTitle(),
slot=mapper.map,
tooltip='Show {0} dock'.format(dock.windowTitle())
)
mapper.setMapping(action, dock)
self.actions.append(action)
mapper.mapped.connect(self.toggle_dock_widget)
help_menu = main_window.menuBar().addMenu('&View')
setattr(help_menu, "no_toolbar_policy", True)
add_actions(help_menu, tuple(self.actions))
def toggle_dock_widget(self, dock_widget):
print("toggle_dock_widget")
The menu is populated with all QDockWidget windowTitles but when i press each of them the slot toggle_dock_widget is not called. create_action is a helper which creates the QAction and connect the triggered signal to slot.
The thing is, I don't really understand quite well how QSignalMapper works but my intuition tells me it's the right choice for this particular problem.
What could I be missing here?
There's aleady a built-in dock-widget menu. Just right-click any dock title-bar, or any tool-bar or menu-bar. See: QMainWindow::createPopupMenu.
PS:
The reason why your QSignalMapper code doesn't work is probably because you are connecting to the wrong overload of the mapped signal. Try this instead:
mapper.mapped[QtWidgets.QWidget].connect(self.toggle_dock_widget)

Customising location-sensitive context menu in QTextEdit

I am trying to adjust the context menu in a QTextEdit. I have succeeded in getting access to and then displaying the default menu with the following code:
class LinkTextBrowser(QTextBrowser):
def contextMenuEvent(self, event):
menu = self.createStandardContextMenu(event.pos())
# do stuff to menu here
menu.popup(event.globalPos())
However, this does not work for location-sensitive clicks. The case in question is the "Copy Link Location" item in a QTextBrowser's right click menu, which is only enabled if you right click on a link, for obvious reasons. I can't get it to ever be enabled. I suspect I am passing the wrong position to createStandardContextMenu, but I can't figure out the correct position to feed it.
I have tried both event.globalPos() and event.pos(), neither of which work. I also looked at the source code for QTextEdit, but didn't get anywhere. What position is it expecting?
Edit: Update: It appears the problem is the scrolling in the TextBrowser; if I scroll to the top of the window and use event.pos() it behaves. I don't have working code yet, but correcting for the scroll is the solution.
(Specifically, I want to disconnect the signal emitted by the Copy Link Location action and connect it to my own function so I can adjust the URL before copying it to the clipboard, allowing me to make links absolute and so forth before copying, and I have no particular desire to re-write the working bits.)
Here is the working transform of the coordinates:
class LinkTextBrowser(QTextBrowser):
def contextMenuEvent(self, event):
self.link_pos = event.pos()
# correct for scrolling
self.link_pos.setX(self.link_pos.x() + self.horizontalScrollBar().value())
self.link_pos.setY(self.link_pos.y() + self.verticalScrollBar().value())
menu = self.createStandardContextMenu(self.link_pos)
# do stuff to menu
menu.popup(event.globalPos())
Try self.mapToGlobal(event.pos()), it should take into account scroll position.
Maybe you can try something like:
QMenu *menu = new QMenu();
menu->addAction(...);
menu->exec(textEdit->mapToGlobal(pos));
It's C++ but I'm sure that you can easy convert it to python.

pyQt4 QGraphicsView on mouse event help needed

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)

Tooltips or status bar not working in a PyQt app from Maya

I've got a PyQt4 QDialog that I'm launching from python in Autodesk Maya. I want to have a status bar in the window or, if need be, tooltips. Maya doesn't seem to approve of either. I've implemented it using the method described here:
http://www.qtcentre.org/threads/10593-QDialog-StatusBar
If I launch my app standalone, both work correctly. Running from Maya, though, the status updates get sent to the general Maya status bar (which is not very obvious if you're in a different window), and Maya seems to steal the events completely from me: if I monitor the events that my event() method is getting, it never gets a QEvent.StatusTip event. I've tried swapping my QDialog for a QMainWindow, but it doesn't seem to change anything.
Any suggestions for avenues to look down to get this working?
At the moment, I'm working around this in a horrible way: subclassing each of widgets I want to use, and adding a signal to send to the parent, self.setMouseTracking(True), and a mouseMoveEvent(self, e) that sends the signal to the parent. Then at the top of the tree I set the status bar. It's the sort of nasty code that makes me feel dirty, subclassing all the widget types, but it does seem to be working.
Any better suggestions VERY gratefully received!
I need to tackle this as well, so your post was quite helpful.
When I have encountered event issues like this before, I solved it by using installEventFilter on all widgets (the same filter), rather than subclassing. Then you can receive and accept the events to block them from Maya (or let them through, e.g. space bar for marking menus over your gui, etc)
Here is what I use to let Maya have the spacebar (marking menus), ctrl+A (attribute editor toggle) and ctrl+Z (undo). This would be added to your event filter:
if event.type() == QEvent.KeyPress:
key = event.key()
mod = event.modifiers()
if ((ctrla and key == Qt.Key_A and mod == Qt.ControlModifier) or # CTRL+A
(ctrlz and key == Qt.Key_Z and mod == Qt.ControlModifier) or # CTRL+Z
(space and key == Qt.Key_Space)): # Space Bar
event.ignore()
return True
return False
You would just need to do the opposite and use event.accept() and return False
For QWidgets, colts answer here is pretty good.
This is how I got it working for QActions:
class ActionFn(object):
def __init__(self, action):
self.action = action
def __call__(self):
self.action.parent()._displayStatusTip(self.action.statusTip())
Then after the action is created:
newAction._statusFn = _StatusTipActionFn(newAction)
newAction.hovered.connect(newAction._statusFn)
I hope this helps.

Categories

Resources