[Maya] PysideでMayaにDockingするWindowの作り方

MayaにDockingするWindowを作ってみた。


# -*- coding: utf-8 -*-
import os
from functools import partial
import time
import imp
import random

"""
PySide2モジュールを探し、ある場合はそちらをインポートします。
"""
try:
    imp.find_module('PySide2')
    from PySide2.QtWidgets import *
    from PySide2.QtGui import *
    from PySide2.QtCore import *

except ImportError:
    from PySide.QtGui import *
    from PySide.QtCore import *


LOGO_IMAGE = r"画像のパスをここに入れてください。"


def get_maya_pointer():
    """
    Mayaのメインウィンドウを取得する関数
    """
    try:
        import maya.cmds as cmds
        from maya import OpenMayaUI

    except ImportError:
        return None

    """
    実は2017ではshibokenも2になっているので、あればshiboken2をインポートします。
    """
    try:
        imp.find_module("shiboken2")
        import shiboken2
        return shiboken2.wrapInstance(long(OpenMayaUI.MQtUtil.mainWindow()), QWidget)

    except ImportError:
        import shiboken
        return shiboken.wrapInstance(long(OpenMayaUI.MQtUtil.mainWindow()), QWidget)

from maya.app.general.mayaMixin import MayaQWidgetBaseMixin, MayaQWidgetDockableMixin

#class Example_connectAttr(MayaQWidgetDockableMixin, QScrollArea):
class Example_connectAttr(MayaQWidgetDockableMixin, QMainWindow):
    def __init__(self, node=None, *args, **kwargs):
        super(Example_connectAttr, self).__init__(*args, **kwargs)
        # Member Variables
        self.nodeName = node               # Node name for the UI
        self.attrUI = None                 # Container widget for the attr UI widgets
        self.attrWidgets = {}              # Dict key=attrName, value=widget
        
        randomInt=random.randint(0,9999)
        self.setObjectName("MyDock_Window"+str(randomInt))
        self.setWindowTitle("MyDock Window")
        self._initUI()
        
        
    def _initUI(self):
        wrapper = QWidget()
        self.setCentralWidget(wrapper)

        mainLayout = QVBoxLayout()
        wrapper.setLayout(mainLayout)
        

def start():
    maya_win = get_maya_pointer()
    ui = Example_connectAttr(node = maya_win)
    ui.show(dockable=True, floating=True)
    return ui

print("__name__ = "+__name__)
if __name__ == '__main__' or __name__ == "NppMaya" or __name__ == "main":

    app = QApplication.instance()
    if app is None:
        app = QApplication([])
    ui = start()
    app.exec_()

pyside2 delete QVBoxLayout remove clear

更新機能がめんどくさいPysideの表示リフレッシュのために

レイアウト内をちゃんと削除するために

def clearLayout(self, layout):
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                self.clearLayout(item.layout())

QtDesigner Pyside Qtab Resizable リサイズ可能な 可変 のタブ

短く書けばこれだ。

          <widget class="QTabWidget" name="tabWidget_1">
           <property name="currentIndex">
            <number>0</number>
           </property>
           <widget class="QWidget" name="tab_3">
            <attribute name="title">
             <string>Tab 1</string>
            </attribute>
            <layout class="QGridLayout" name="gridLayout_4">
             <item row="0" column="0">
              <widget class="QDateTimeEdit" name="dateTimeEdit_2"/>
             </item>
             <item row="1" column="0">
              <widget class="QDateTimeEdit" name="dateTimeEdit"/>
             </item>
            </layout>
           </widget>
           <widget class="QWidget" name="tab_4">
            <attribute name="title">
             <string>Tab 2</string>
            </attribute>
            <layout class="QGridLayout" name="gridLayout_5">
             <item row="0" column="0">
              <widget class="QCheckBox" name="checkBox_2">
               <property name="text">
                <string>CheckBox</string>
               </property>
              </widget>
             </item>
             <item row="1" column="0">
              <widget class="QCheckBox" name="checkBox">
               <property name="text">
                <string>CheckBox</string>
               </property>
              </widget>
             </item>
            </layout>
           </widget>
          </widget>

ファイルとして成立させるならこうだ。

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1146</width>
    <height>794</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout_2">
    <item>
     <layout class="QVBoxLayout" name="verticalLayout">
      <item>
       <layout class="QHBoxLayout" name="horizontalLayout">
        <item>
         <widget class="QGroupBox" name="groupBox">
          <property name="title">
           <string>GroupBox</string>
          </property>
          <layout class="QVBoxLayout" name="verticalLayout_9">
           <item>
            <layout class="QVBoxLayout" name="verticalLayout_6">
             <item>
              <widget class="QLabel" name="label_3">
               <property name="text">
                <string>TextLabel</string>
               </property>
              </widget>
             </item>
             <item>
              <widget class="QLabel" name="label_4">
               <property name="text">
                <string>TextLabel</string>
               </property>
              </widget>
             </item>
            </layout>
           </item>
          </layout>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="horizontalLayout_2">
        <item>
         <widget class="QGroupBox" name="groupBox_2">
          <property name="title">
           <string>GroupBox</string>
          </property>
          <layout class="QVBoxLayout" name="verticalLayout_8">
           <item>
            <layout class="QVBoxLayout" name="verticalLayout_7">
             <item>
              <widget class="QLabel" name="label">
               <property name="text">
                <string>TextLabel</string>
               </property>
              </widget>
             </item>
             <item>
              <widget class="QLabel" name="label_2">
               <property name="text">
                <string>TextLabel</string>
               </property>
              </widget>
             </item>
            </layout>
           </item>
          </layout>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="horizontalLayout_3">
        <item>
         <widget class="QGroupBox" name="groupBox_3">
          <property name="title">
           <string>GroupBox</string>
          </property>
          <layout class="QVBoxLayout" name="verticalLayout_3">
           <item>
            <layout class="QVBoxLayout" name="verticalLayout_4">
             <item>
              <widget class="QLabel" name="label_6">
               <property name="text">
                <string>TextLabel</string>
               </property>
              </widget>
             </item>
             <item>
              <layout class="QVBoxLayout" name="verticalLayout_5"/>
             </item>
             <item>
          <widget class="QTabWidget" name="tabWidget_1">
           <property name="currentIndex">
            <number>0</number>
           </property>
           <widget class="QWidget" name="tab_3">
            <attribute name="title">
             <string>Tab 1</string>
            </attribute>
            <layout class="QGridLayout" name="gridLayout_4">
             <item row="0" column="0">
              <widget class="QDateTimeEdit" name="dateTimeEdit_2"/>
             </item>
             <item row="1" column="0">
              <widget class="QDateTimeEdit" name="dateTimeEdit"/>
             </item>
            </layout>
           </widget>
           <widget class="QWidget" name="tab_4">
            <attribute name="title">
             <string>Tab 2</string>
            </attribute>
            <layout class="QGridLayout" name="gridLayout_5">
             <item row="0" column="0">
              <widget class="QCheckBox" name="checkBox_2">
               <property name="text">
                <string>CheckBox</string>
               </property>
              </widget>
             </item>
             <item row="1" column="0">
              <widget class="QCheckBox" name="checkBox">
               <property name="text">
                <string>CheckBox</string>
               </property>
              </widget>
             </item>
            </layout>
           </widget>
          </widget>
             </item>
             <item>
              <widget class="QLabel" name="label_5">
               <property name="text">
                <string>TextLabel</string>
               </property>
              </widget>
             </item>
            </layout>
           </item>
          </layout>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1146</width>
     <height>26</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

元ネタはこちら

https://stackoverflow.com/questions/6221551/qtabwidget-refusing-to-auto-resize

QTreeView Get Selected Text (pyside2)(python3)


# -*- coding: utf-8 -*-
import os
from functools import partial
import time
import imp

"""
PySide2モジュールを探し、ある場合はそちらをインポートします。
"""
try:
    imp.find_module('PySide2')
    from PySide2.QtWidgets import *
    from PySide2.QtGui import *
    from PySide2.QtCore import *

except ImportError:
    from PySide.QtGui import *
    from PySide.QtCore import *


LOGO_IMAGE = r"画像のパスをここに入れてください。"


def get_maya_pointer():
    """
    Mayaのメインウィンドウを取得する関数
    """
    try:
        import maya.cmds as cmds
        from maya import OpenMayaUI

    except ImportError:
        return None

    """
    実は2017ではshibokenも2になっているので、あればshiboken2をインポートします。
    """
    try:
        imp.find_module("shiboken2")
        import shiboken2
        return shiboken2.wrapInstance(int(OpenMayaUI.MQtUtil.mainWindow()), QWidget)

    except ImportError:
        import shiboken
        return shiboken.wrapInstance(int(OpenMayaUI.MQtUtil.mainWindow()), QWidget)





class TreeView_Selected_Text(QMainWindow):


    def __init__(self, parent = None):
        super(TreeView_Selected_Text, self).__init__(parent)
        self.setObjectName("TreeView_Selected_Text")
        self.setWindowTitle("TreeView_Selected_Text")
        self._initUI()
        self.errorDialog = QErrorMessage(self) # QErrorMessageインスタンスの保持


    def _initUI(self):
        wrapper = QWidget()
        self.setCentralWidget(wrapper)

        mainLayout = QVBoxLayout()
        wrapper.setLayout(mainLayout)

        #-----------------------------------------------------------------------

        #-----------------------------------------------------------------------
        # fifth row
        #-----------------------------------------------------------------------
        fifthHorizontalArea = QHBoxLayout()
        fifthHorizontalArea.setSpacing(20)
        mainLayout.addLayout(fifthHorizontalArea)

        fifthHorizontalArea.addWidget(self._makeTreeWidget())

        mainLayout.addWidget(self._makeHorizontalLine())

        #-----------------------------------------------------------------------


    def _makeHorizontalLine(self):
        hline = QFrame()
        hline.setFrameShape(QFrame.HLine)
        hline.setFrameShadow(QFrame.Sunken)
        return hline





    def _makeTreeWidget(self):
        """
        QTreeWidgetを作成する関数
        """
        treeWidget = QTreeWidget()
        headerLabels = ["Name", "Age"]
        treeWidget.setColumnCount(len(headerLabels))
        treeWidget.setHeaderLabels(headerLabels)
        treeWidget.setAlternatingRowColors(True)
        treeData = {
            "Male":[
                {"name":"Taro",     "age":"25"},
                {"name":"Ichiro",   "age":"50"},
                {"name":"Jiro",     "age":"40"}
            ],
            "Female":[
                {"name":"Hanako",   "age":"30"}
            ]
        }

        #for sex, profiles in treeData.iteritems():
        for sex, profiles in treeData.items():
            topItem = QTreeWidgetItem([sex])
            treeWidget.addTopLevelItem(topItem)

            for profile in profiles:
                childItem = QTreeWidgetItem(topItem, [profile.get("name"), profile.get("age")])

        treeWidget.expandAll()
        self.treeWidget=treeWidget
        self.treeWidget.selectionModel().selectionChanged.connect(self.treeWidget_selectionChanged)
        
        return treeWidget
    def treeWidget_selectionChanged(self,selected, deselected):
        print("----treeWidget_selectionChanged-----")
        
        
        for QModelIndex in self.treeWidget.selectedIndexes():
            text = QModelIndex.data(Qt.DisplayRole) # or ix.data()
            print("text= "+str(text))
            
            QModelIndex2=QModelIndex.child(0,0).sibling(0,0)
            text2 = QModelIndex2.data(Qt.DisplayRole)   
            print("text2= "+str(text2))   
            QModelIndex3=QModelIndex.child(0,0).sibling(0,1)
            text3 = QModelIndex3.data(Qt.DisplayRole)   
            print("text3= "+str(text3))   



def start():
    maya_win = get_maya_pointer()
    ui = TreeView_Selected_Text(parent = maya_win)
    ui.show()
    return ui


if __name__ == '__main__':

    app = QApplication.instance()
    if app is None:
        app = QApplication([])
    ui = start()
    app.exec_()