DragAndDrop(2)

本教程介绍如何使用PySide2在Maya中创建一个带有文件浏览器的文本编辑器,支持拖放功能,用于快速打开和编辑脚本文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
"""
Author: Virgil
Date: 2020/6/13 14:38
"""

from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets
from shiboken2 import wrapInstance

import maya.OpenMayaUI as omui
import maya.cmds as cmds
import maya.mel as mel

def maya_main_window():
    """
    Return the Maya main window widget as a Python object
    """
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)

class TextEditor(QtWidgets.QPlainTextEdit):
    def __init__(self, parent=None):
        super(TextEditor, self).__init__(parent)

    def open_file(self, file_path):
        if file_path:
            file_info = QtCore.QFileInfo(file_path)
            if file_info.exists and file_info.isFile():

                f = QtCore.QFile(file_info.absoluteFilePath())
                if f.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
                    text_stream = QtCore.QTextStream(f)
                    text_stream.setCodec("UTF-8")

                    text = text_stream.readAll()
                    f.close()

                    self.setPlainText(text)

    def dragEnterEvent(self, event):
        if event.mimeData().hasText() or event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event):
        if event.mimeData().hasUrls():
            urls = event.mimeData().urls()

            file_path = urls[0].toLocalFile()
            self.open_file(file_path)

            return

        super(TextEditor, self).dropEvent(event)

class CustomDialog(QtWidgets.QDialog):
    WINDOW_TITLE = "File Explorer Drag And Drop"
    
    dlg_instance = None
    def __init__(self, parent=maya_main_window()):
        super(CustomDialog, self).__init__(parent)

        self.setWindowTitle(self.WINDOW_TITLE)
        self.setMinimumSize(800, 400)
        self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)

        self.create_widgets()
        self.create_layout()
        self.create_connections()

    def create_widgets(self):
        self.editor = TextEditor()

        self.clear_bttn = QtWidgets.QPushButton("Clear")
        self.close_bttn = QtWidgets.QPushButton("Close")

        self.create_tree_view()

    def create_tree_view(self):
        # root_path = "{0}scripts".format(cmds.internalVar(userAppDir=True))
        root_path = "D:/Workspace/PyCharm"

        self.model = QtWidgets.QFileSystemModel()
        self.model.setRootPath(root_path)

        self.tree_view = QtWidgets.QTreeView()
        self.tree_view.setModel(self.model)
        self.tree_view.setRootIndex(self.model.index(root_path))
        self.tree_view.hideColumn(1)
        self.tree_view.hideColumn(3)
        self.tree_view.setColumnWidth(0, 240)
        self.tree_view.setFixedWidth(360)

        self.tree_view.setDragEnabled(True)

        self.model.setNameFilters(["*.py"])
        self.model.setNameFilterDisables(False)

    def create_layout(self):
        side_bar_layout = QtWidgets.QHBoxLayout()
        side_bar_layout.addWidget(self.tree_view)
        side_bar_layout.addWidget(self.editor)

        button_layout = QtWidgets.QHBoxLayout()
        button_layout.addSpacing(4)
        button_layout.addStretch()
        button_layout.addWidget(self.clear_bttn)
        button_layout.addWidget(self.close_bttn)

        main_layout = QtWidgets.QVBoxLayout(self)
        main_layout.setContentsMargins(5, 5, 5, 5)
        main_layout.addLayout(side_bar_layout)
        main_layout.addLayout(button_layout)

    def create_connections(self):
        self.tree_view.doubleClicked.connect(self.open_file)

        self.clear_bttn.clicked.connect(self.clear_editor)
        self.close_bttn.clicked.connect(self.close)

    def clear_editor(self):
        # self.editor.clear()
        self.editor.setPlainText("")

    def open_file(self, index):
        print("TODO: open_file()")
        file_path = self.model.filePath(index)

        file_info = QtCore.QFileInfo(file_path)
        if file_info.exists and file_info.isFile():

            f = QtCore.QFile(file_info.absoluteFilePath())
            if f.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
                text_stream = QtCore.QTextStream(f)
                text_stream.setCodec("UTF-8")

                text = text_stream.readAll()
                f.close()

                self.editor.setPlainText(text)


def showWindow():
    global dialog
    try:
        dialog.close()
        dialog.deleteLater()
    except:
        pass

    dialog = CustomDialog()
    dialog.show()

if __name__ == "__main__":
    try:
        dialog.close()
        dialog.deleteLater()
    except:
        pass

    dialog = CustomDialog()
    dialog.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值