首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pyRevit WPF非模式故障

pyRevit WPF非模式故障
EN

Stack Overflow用户
提问于 2020-05-14 16:47:24
回答 1查看 349关注 0票数 2

所以我才刚刚开始尝试pyRevit中的WPF。我尝试像这样实现pyrevit.forms.WPFWindow类:

代码语言:javascript
复制
# -*- coding: UTF-8 -*-
"""
Third-Party software credits:
pyRevit: repository at https://github.com/eirannejad/pyRevit
"""

import System, clr, json, sys
clr.AddReference("System.Windows.Forms")
clr.AddReference('IronPython.Wpf')
import wpf
from Autodesk.Revit.DB import *
from pyrevit import revit, script, forms

class FactorySettings(forms.WPFWindow):

    def __init__(self):
        forms.WPFWindow.__init__(self, script.get_bundle_file('settings.xaml'))

    def something_click(self, A, B):
        plantings = FilteredElementCollector(revit.doc) \
            .WhereElementIsElementType() \
            .OfCategory(BuiltInCategory.OST_Planting)

ui = FactorySettings()
ui.show()

这是我的xaml:

代码语言:javascript
复制
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:Collections="clr-namespace:System.Collections;assembly=mscorlib"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        mc:Ignorable="d"
        ShowInTaskbar="False" ResizeMode="CanResize"
        WindowStartupLocation="CenterScreen"
        HorizontalContentAlignment="Center"
        Title="Set worksets" Width="300" SizeToContent="Height"
        >
    <StackPanel Margin="0,0,0,0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <Button Content="Do something" Name="something" Click="something_click"/>
    </StackPanel>

</Window>

由于def show(self, modal=False):类函数的原因,这将打开一个非模态窗口。对我来说,问题是即使我的单击函数只调用FilteredElementCollector对象,Revit也会崩溃。如果我使用ui.show(modal=True),它将正常工作,但之后我将无法在Revit UI中执行任何操作。我真正想做的是:

代码语言:javascript
复制
def something_click(self, A, B):
    if self.PHfamSymbol != None:
         with forms.WarningBar(title='Place an instance of the placeholder object.'):
            revit.uidoc.PromptForFamilyInstancePlacement(self.PHfamSymbol)

这是行不通的,因为焦点仍然在UI上。我试过这个:

代码语言:javascript
复制
def something_click(self, A, B):
    if self.PHfamSymbol != None:
        self.Close()
         with forms.WarningBar(title='Place an instance of the placeholder object.'):
            try:
                revit.uidoc.PromptForFamilyInstancePlacement(self.PHfamSymbol)
            except:
                pass

这是可行的,但我需要在完成后创建一个新的UI实例。有没有可能在pyRevit中使用非模态UI?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-15 15:59:44

您需要使用ExternalEvent在非模式窗口中与Revit进行交互。您在pyRevitMEP中有许多示例。我做了一个reusable class here。我在许多pyRevitMEP脚本中使用它,比如Element3DRotation。你也可以看看我以前的博客[Revit API] Simple Modeless Form (External Event Handler) in pyRevit文章,它引用了更多的资源和更多的评论。

示例

脚本

代码语言:javascript
复制
"""
Copyright (c) 2017 Cyril Waechter
Python scripts for Autodesk Revit

This file is part of pypevitmep repository at https://github.com/CyrilWaechter/pypevitmep

pypevitmep is an extension for pyRevit. It contain free set of scripts for Autodesk Revit:
you can redistribute it and/or modify it under the terms of the GNU General Public License
version 3, as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/CyrilWaechter/pypevitmep/blob/master/LICENSE
"""
from Autodesk.Revit.UI import IExternalEventHandler, ExternalEvent
from Autodesk.Revit.DB import Transaction
from Autodesk.Revit.Exceptions import InvalidOperationException
import rpw
from pyrevit.forms import WPFWindow
doc = rpw.revit.doc
uidoc = rpw.revit.uidoc

__doc__ = "A simple modeless form sample"
__title__ = "Modeless Form"
__author__ = "Cyril Waechter"
__persistentengine__ = True

# Simple function we want to run
def delete_elements():
    with rpw.db.Transaction("Delete selection"):
        for elid in uidoc.Selection.GetElementIds():
            doc.Delete(elid)

# Create a subclass of IExternalEventHandler
class SimpleEventHandler(IExternalEventHandler):
    """
    Simple IExternalEventHandler sample
    """

    # __init__ is used to make function from outside of the class to be executed by the handler. \
    # Instructions could be simply written under Execute method only
    def __init__(self, do_this):
        self.do_this = do_this

    # Execute method run in Revit API environment.
    def Execute(self, uiapp):
        try:
            self.do_this()
        except InvalidOperationException:
            # If you don't catch this exeption Revit may crash.
            print "InvalidOperationException catched"

    def GetName(self):
        return "simple function executed by an IExternalEventHandler in a Form"


# Now we need to make an instance of this handler. Moreover, it shows that the same class could be used to for
# different functions using different handler class instances
simple_event_handler = SimpleEventHandler(delete_elements)
# We now need to create the ExternalEvent
ext_event = ExternalEvent.Create(simple_event_handler)

# A simple WPF form used to call the ExternalEvent
class ModelessForm(WPFWindow):
    """
    Simple modeless form sample
    """

    def __init__(self, xaml_file_name):
        WPFWindow.__init__(self, xaml_file_name)
        self.simple_text.Text = "Hello World"
        self.Show()

    def delete_click(self, sender, e):
        # This Raise() method launch a signal to Revit to tell him you want to do something in the API context
        ext_event.Raise()

# Let's launch our beautiful and useful form !
modeless_form = ModelessForm("ModelessForm.xaml")

xaml文件

代码语言:javascript
复制
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Delete things:" Height="150" Width="300" ShowInTaskbar="False" Topmost="True"
        WindowStartupLocation="CenterScreen" ScrollViewer.VerticalScrollBarVisibility="Disabled" HorizontalContentAlignment="Center">
    <StackPanel Margin="20" HorizontalAlignment="Stretch">
        <TextBlock x:Name="simple_text" Text="" Grid.Column="0" HorizontalAlignment="Center" FontWeight="Bold"/>
        <Button Content="Delete selected elements" Height="30" Margin="10,10" Click="delete_click"/>
    </StackPanel>
</Window>
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61793050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档