assemblyReference踩坑记录


import maya.cmds as cmds
import maya.OpenMayaUI as omui
from shiboken2 import wrapInstance
from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QProgressBar
from PySide2.QtCore import QTimer
import asyncio

def get_maya_main_window():
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(int(main_window_ptr), QWidget)

class MayaMainWindow(QMainWindow):
    def __init__(self):
        super().__init__(parent=get_maya_main_window())
        self.init_ui()

    def init_ui(self):
        # 设置窗口
        self.setWindowTitle("Maya PySide2 异步示例")
        self.setGeometry(300, 300, 300, 200)

        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 创建按钮和进度条
        self.button = QPushButton("开始任务", self)
        self.progress_bar = QProgressBar(self)

        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.button)
        layout.addWidget(self.progress_bar)
        central_widget.setLayout(layout)
        self.running = False

        # 事件绑定
        self.button.clicked.connect(self.start_task_async)

    async def do_long_task(self):
        self.running = True
        for i in range(1, 10):
            await asyncio.to_thread(partial(time.sleep, 2))  # 模拟耗时操作
            print(i, i)
        self.running = False
        
        return 'sdffsda'

    async def update_progress_bar(self):
        i=0
        while True:
            await asyncio.sleep(0.5)  # 异步等待
            if self.running:
                print(i)
                self.progress_bar.setValue(i % 100)
                i += 1
            else:
                return

    def start_task_async(self):
        loop = asyncio.get_event_loop()

        async def main_task():
            task_completed = asyncio.create_task(self.do_long_task())
            _ = asyncio.create_task(self.update_progress_bar())

            rel = await task_completed
            self.progress_bar.setValue(0)  # 任务完成后重置进度条
            return rel

        rel = loop.run_until_complete(main_task())
        print(rel)
        return rel


window = MayaMainWindow()
window.show()

评论
  目录