Aleksei Rusev Houdini Selection To QWidget Callback

Created by Aleksei Rusev
import hou
from PySide2 import QtWidgets
from PySide2 import QtCore
from SelectionEvent import SelectionEvent

# Simple example widget, put it in Houdini's Python panel and see the result
class MyWidget(QtWidgets.QFrame):
    SelectionChanged = QtCore.Signal(tuple) #  Usefull to have a signal here

    def __init__(self):
        super(MyWidget, self).__init__()
        self.le = QtWidgets.QTextEdit()
        l = QtWidgets.QVBoxLayout()
        SelectionEvent.install_selection_event(self)  # Pass QWidget where you whant to catch SelectionEvent

    def event(self, event):
    # Override event method and catch SelectionEvent here
        if event.type() == SelectionEvent.Type:
            if event.selection:
                self.SelectionChanged.emit(event.selection) #  Emit signal, selection is the result of hou.selectedNodes()
                return True
        return super(MyWidget, self).event(event)

    def closeEvent(self, event):
    # Remove event from Houdini's callback
import hou
from PySide2 import QtWidgets
from PySide2 import QtCore

class SelectionEvent(QtCore.QEvent):
    Event to catch Houdinij's node selection change event and post it to interested QWidget
    Usage: In your main widget, call SelectionEvent.install_selection_event(self)
    Override event() method and catch SelectionEvent there:
    def event(self, event):
        if event.type() == SelectionEvent.Type:
            print 'Selection changed to: ', event.selection
    IMPORTANT: Don't forget to remove the event from Houdini's event loop by calling: SelectionEvent.remove_selection_event()
    Type = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())

    def __init__(self, selection):
        self.selection = selection
        super(SelectionEvent, self).__init__(self.Type)

    def install_selection_event(widget):
        def event_callback():
            def post_event(sel):
                sel_event = SelectionEvent(sel)
                QtWidgets.QApplication.instance().postEvent(widget, sel_event)

            cur_selection = hou.selectedNodes()
            if getattr(hou.session, '_selection', None) != cur_selection:
                hou.session._selection = cur_selection
                return post_event(cur_selection)
            hou.session._selection = cur_selection
        if getattr(hou.session, '_selection_cb', None):
        hou.session._selection_cb = event_callback

    def remove_selection_event():
        if hasattr(hou.session, '_selection_cb'):
            for cb in hou.ui.eventLoopCallbacks():
                if cb == getattr(hou.session, '_selection_cb', None):
                    del hou.session._selection_cb

Comments (0)