【问题标题】:Split pane gui object拆分窗格 gui 对象
【发布时间】:2011-10-08 15:00:57
【问题描述】:

我已经开发了一段时间的 gui,它需要创建 Mathematica 所缺乏的通用控件对象(例如微调器、树视图、openerbar 等)。一种是多面板,即一个面板对象,它被分成两个(或更多)子面板,其中的分隔符可以通过鼠标设置。这是我的双窗格版本。我想听听您关于如何将其扩展为不仅可以处理 2 个子窗格,还可以处理任意数量的子窗格以及如何优化它的意见和想法。目前,对于负载很重的子窗格,它非常滞后,不知道为什么。

Options[SplitPane] = {Direction -> "Vertical", 
   DividerWidth -> Automatic, Paneled -> {True, True}};
SplitPane[opts___?OptionQ] := 
  Module[{dummy}, SplitPane[Dynamic[dummy], opts]];
SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];
SplitPane[val_, content_, opts___?OptionQ] := 
  SplitPane[val, content, {100, 50}, opts];
SplitPane[Dynamic[split_, arg___], {expr1_, expr2_}, {maxX_, maxY_}, 
   opts___?OptionQ] := 
  DynamicModule[{temp, dir, d, panel, coord, max, fix, val},
   {dir, d, panel} = {Direction, DividerWidth, Paneled} /. {opts} /. 
     Options[SplitPane];
   dir = dir /. {Bottom | Top | "Vertical" -> "Vertical", _ -> 
       "Horizontal"};
   d = d /. Automatic -> 2;
   split = If[NumberQ[split], split, max/2];
   val = Clip[split /. {_?NumberQ -> split, _ -> maxX/2}, {0, maxX}];
   {coord, max, fix} = 
    Switch[dir, "Vertical", {First, maxX, maxY}, 
     "Horizontal", {(max - Last[#]) &, maxY, maxX}];
   panel = (# /. {None | False -> 
          Identity, _ -> (Panel[#, ImageMargins -> 0, 
             FrameMargins -> -1] &)}) & /@ panel;

   Grid[If[dir === "Vertical",
     {{
       Dynamic[
        panel[[1]]@
         Pane[expr1, ImageSize -> {split - d, fix}, 
          ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, 
          AppearanceElements -> None], TrackedSymbols :> {split}],
       Deploy@EventHandler[
         MouseAppearance[
          Pane[Null, ImageSize -> {d*2, fix}, ImageMargins -> -1, 
           FrameMargins -> -1], "FrameLRResize"],
         "MouseDown" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = 
            If[Abs[temp - split] <= d \[And] 0 <= temp <= max, temp, 
             split]), 
         "MouseDragged" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = If[0 <= temp <= max, temp, split])],
       Dynamic@
        panel[[2]]@
         Pane[expr2, ImageSizeAction -> "Scrollable", 
          Scrollbars -> Automatic, AppearanceElements -> None, 
          ImageSize -> {max - split - d, fix}]
       }},
     {
      List@
       Dynamic[panel[[1]]@
         Pane[expr1, ImageSize -> {fix, split - d}, 
          ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, 
          AppearanceElements -> None], TrackedSymbols :> {split}],
      List@Deploy@EventHandler[
         MouseAppearance[
          Pane[Null, ImageSize -> {fix, d*2}, ImageMargins -> -1, 
           FrameMargins -> -1], "FrameTBResize"],
         "MouseDown" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = 
            If[Abs[temp - split] <= d \[And] 0 <= temp <= max, temp, 
             split]), 
         "MouseDragged" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = If[0 <= temp <= max, temp, split])],
      List@
       Dynamic[panel[[2]]@
         Pane[expr2, ImageSizeAction -> "Scrollable", 
          Scrollbars -> Automatic, 
          ImageSize -> {fix, max - split - d}, 
          AppearanceElements -> None], TrackedSymbols :> {split}]
      }
     ], Spacings -> {0, -.1}]
   ];
SplitPane[val_, arg___] /; NumberQ[val] := 
  Module[{x = val}, SplitPane[Dynamic[x], arg]];

pos = 300;
SplitPane[
 Dynamic[pos], {Manipulate[
   Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}], 
  Factorial[123]}, {500, 300}]

【问题讨论】:

  • 令人印象深刻!至于优化:如何使用 ControlActive 和/或 SynchronousUpdating 选项?
  • 非常好的工作,但请记住,您的“问题”格式不适合该网站。这里的 Mma 社区对此通常是宽容的,但请尽量根据网站的一般规则制定您的问题,以避免关闭(和删除)投票。

标签: user-interface wolfram-mathematica


【解决方案1】:

推广到多个面板的关键是重构您的代码。在目前的形式中,虽然非常好,但它混合了可视化/UI 原语和选项与拆分逻辑,并且有很多重复的代码。这使得泛化变得困难。这是重构后的版本:

ClearAll[SplitPane];
Options[SplitPane] = {
    Direction -> "Vertical", DividerWidth -> Automatic, Paneled -> True
};
SplitPane[opts___?OptionQ] :=   Module[{dummy}, SplitPane[Dynamic[dummy], opts]];
SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];
SplitPane[val_, content_, opts___?OptionQ] :=
    SplitPane[val, content, {100, 50}, opts];
SplitPane[sp_List, {cont__}, {maxX_, maxY_}, opts___?OptionQ] /; 
        Length[sp] == Length[Hold[cont]] - 1 :=
  Module[{scrollablePane, dividerPane, onMouseDownCode, onMouseDraggedCode, dynPane,
      gridArg, split, divider, panel},
    With[{paneled = Paneled /. {opts} /. Options[SplitPane],len = Length[Hold[cont]]},
       Which[
          TrueQ[paneled ],
             panel = Table[True, {len}],
          MatchQ[paneled, {Repeated[(True | False), {len}]}],
             panel = paneled,
          True,
            Message[SplitPane::badopt]; Return[$Failed, Module]
       ]
    ];

    DynamicModule[{temp, dir, d, coord, max, fix, val},
      {dir, d} = {Direction, DividerWidth}/.{opts}/.Options[SplitPane];
      dir =  dir /. {
         Bottom | Top | "Vertical" -> "Vertical", _ -> "Horizontal"
      };
      d = d /. Automatic -> 2;
      val = Clip[sp /. {_?NumberQ -> sp, _ -> maxX/2}, {0, maxX}];
      {coord, max, fix} =
        Switch[dir,
          "Vertical",
             {First, maxX, maxY},
          "Horizontal",
             {(max - Last[#]) &, maxY, maxX}
        ];
      Do[split[i] = sp[[i]], {i, 1, Length[sp]}];
      split[Length[sp] + 1] = max - Total[sp] - 2*d*Length[sp];
      panel =
          (# /. {
            None | False -> Identity, 
            _ -> (Panel[#, ImageMargins -> 0,FrameMargins -> -1] &)
           }) & /@ panel;
      scrollablePane[args___] :=
          Pane[args, ImageSizeAction -> "Scrollable", 
               Scrollbars -> Automatic, AppearanceElements -> None];
      dividerPane[size : {_, _}] :=
          Pane[Null, ImageSize -> size, ImageMargins -> -1,FrameMargins -> -1];

      onMouseDownCode[n_] := 
        Module[{old},
          temp = coord@MousePosition@"CellContentsAbsolute";
          If[Abs[temp - split[n]] <= d \[And] 0 <= temp <= max,
            old = split[n];
            split[n] = temp-Sum[split[i], {i, n - 1}];
            split[n + 1] += old - split[n];       
        ]];

      onMouseDraggedCode[n_] :=
         Module[{old},
            temp = coord@MousePosition@"CellContentsAbsolute";
            If[0 <= temp <= max,
               old = split[n];
               split[n] = temp -Sum[split[i], {i, n - 1}];
               split[n + 1] += old - split[n];
            ] ;
         ];

      SetAttributes[dynPane, HoldFirst];
      dynPane[expr_, n_, size_] :=
          panel[[n]]@scrollablePane[expr, ImageSize -> size];

      divider[n_, sizediv_, resizeType_] :=
         Deploy@EventHandler[
            MouseAppearance[dividerPane[sizediv], resizeType],
           "MouseDown" :> onMouseDownCode[n],
           "MouseDragged" :> onMouseDraggedCode[n]
         ];

      SetAttributes[gridArg, HoldAll];
      gridArg[{content__}, sizediv_, resizeType_, sizeF_] :=
         Module[{myHold, len = Length[Hold[content]] },
           SetAttributes[myHold, HoldAll];
           List @@ Map[
             Dynamic,
             Apply[Hold, 
                MapThread[Compose,
                   {
                      Range[len] /. {
                        len :>               
                          Function[
                             exp, 
                             myHold[dynPane[exp, len, sizeF[len]]], 
                             HoldAll
                          ],
                        n_Integer :>
                          Function[exp,
                             myHold[dynPane[exp, n, sizeF[n]],
                                divider[n, sizediv, resizeType]
                             ], 
                          HoldAll]
                      },
                      Unevaluated /@ Unevaluated[{content}]
                    }] (* MapThread *)
               ] /. myHold[x__] :> x
           ] (* Map *)
         ]; (* Module *)
      (* Output *)
      Grid[
        If[dir === "Vertical",
           List@ gridArg[{cont}, {d*2, fix},"FrameLRResize",{split[#] - d, fix} &],
           (* else *)
           List /@ gridArg[{cont}, {fix, d*2},"FrameTBResize", {fix, split[#] - d} &]
        ],
        Spacings -> {0, -.1}]]];

SplitPane[val_, arg___] /; NumberQ[val] := 
   Module[{x = val}, SplitPane[Dynamic[x], arg]];

这是它的外观:

SplitPane[{300, 300}, 
 {
   Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}], 
   Factorial[123], 
   CompleteGraph[5]
 }, {900, 300}]

无法评论您提到的性能问题。此外,当您开始用鼠标拖动时,实际光标位置通常相对于分隔线位置非常偏离。这适用于您和我的版本,也许需要一些更精确的缩放。

只是想再次强调一下——泛化只有在我进行重构之后才有可能,将拆分逻辑与可视化相关的事情分开。至于优化,我也觉得这个版本比原来的更容易优化,原因是一样的。

编辑

我有点犹豫是否要添加此注释,但必须指出的是,我上面的解决方案在工作时显示了一种被专业 UI mma 程序员认为不好的做法。即,它使用Module-在Dynamic内部生成变量Module(特别是上面代码中的split,还有各种辅助函数)。我使用它的原因是我无法仅使用DynamicModule- 生成的变量来完成这项工作,再加上Module- 生成的变量以前总是为我工作。但是,请参阅 John Fultz 在this MathGroup 线程中的帖子,他指出应该避免这种做法。

【讨论】:

  • @Sjoerd 确实如此。但我对这个话题很感兴趣。另外,我不是 UI 人,所以有时我会尝试多做一点。
  • Unevaluated /@ Unevaluated[{content}] :)
  • @belisaruis 有什么好笑的?这是将Unevaluated 映射到列表的一种方法:)。尽管内容目前已被评估,但我编写了大部分代码以便它支持未评估的内容,如果我们希望在SplitPane 上施加一些Hold-attributes(好吧,也许这只是一种矫枉过正)。
  • @Leonid 我知道。听起来很有趣。像“嘿!我已经告诉过你不要碰这个!”之类的东西。 :)
  • 干得好。顺便说一句,鼠标位置相对于分隔线位置关闭的原因是因为在onMouseDraggedCode[n_] 中,temp 是分隔线n 相对于左侧(cq 顶部)的新位置frame 但split[n] 存储分隔线相对于其直接邻居的位置。这意味着应该将split[n] 设置为split[n]=temp-Sum[split[i],{i,n-1}] 之类的值。
【解决方案2】:

大量建立在 Leonid 的解决方案之上,这是我的版本。我已经应用了一些更改,主要是为了更容易跟踪动态大小更改,并且因为我根本没有内化 Leonid 的部分代码。

所做的更改:

  • 删除DividerWidth 选项,现在不能由用户设置。没那么重要。
  • 最大水平尺寸(以上帖子中的maxX)已被删除,因为它现在是根据用户指定的面板宽度值计算得出的:w
  • 第一个参数(w,主要动态变量)显式保存面板的宽度,而不是保存分隔线位置。此外,它被制作成一个列表 (w[[n]]) 而不是一个函数(就像 split[n] 在 Leonid 的版本中一样)。
  • 为分隔线添加了最小化/恢复按钮。
  • 限制分隔线移动:分隔线只能从左侧移动到右侧,不能进一步移动。
  • 微调分隔线宽度、ImageMarginsFrameMarginsSpacings 以允许使用零大小的窗格。

仍有待处理的问题:

  • 在最小化/最大化分隔线时,它们应该与最左边/最右边的分隔线重叠。一个 LIFO 分隔器堆栈将解决将分隔器设置为最大的问题,而不是尝试通过它们的按钮更改其他分隔器。这可能会导致一些问题,因为它们会回到以前的状态。堆叠分隔线的问题在于它无法在 Grid 中解决,或者只能通过非常特别调整的负间距来解决。我认为这不值得处理。
  • 将面板缩小到零宽度/高度时出现轻微对齐问题。这是我可以忍受的。

ClearAll[SplitPane];
Options[SplitPane] = {Direction -> "Vertical", Paneled -> True};
SplitPane[opts___?OptionQ] := 
  Module[{dummy = {200, 200}}, SplitPane[Dynamic[dummy], opts]];
SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];
SplitPane[val_, content_, opts___?OptionQ] := 
  SplitPane[val, content, Automatic, opts];
SplitPane[Dynamic[w_], cont_, s_, opts___?OptionQ] :=
  DynamicModule[{
    scrollPane, divPane, onMouseDownCode, onMouseDraggedCode, grid,
    dir, panel, bg, coord, mouse, icon, sizeD, sizeB,
    num, old, pos, origo, temp, max, prev, state, fix},

   {dir, panel} = {Direction, Paneled} /. {opts} /. Options@SplitPane;
   dir = dir /. {Bottom | Top | "Vertical" -> "Vertical", _ -> 
       "Horizontal"};
   bg = panel /. {None | False -> GrayLevel@.9, _ -> None};
   panel = 
    panel /. {None | False -> 
       None, _ -> {RGBColor[0.70588, 0.70588, 0.70588]}}; (* 
   Simulate Panel-like colors on the frame. *)
   fix = s /. {Automatic -> If[dir === "Vertical", 300, 800]};

   (* {coordinate function, mouse cursor, button icon, divider size, 
   button size} *)
   {coord, mouse, icon, sizeD, sizeB} = Switch[dir,
     "Vertical", {First, 
      "FrameLRResize", {"\[RightPointer]", "\[LeftPointer]"}, {5, 
       fix}, {5, 60}},
     "Horizontal", {(max - Last@#) &, 
      "FrameTBResize", {"\[DownPointer]", "\[UpPointer]"}, {fix, 
       7}, {60, 7}}
     ];

   SetAttributes[{scrollPane, grid}, HoldAll];
   (* Framed is required below becase otherwise the horizontal \
version of scrollPane cannot be set to zero height. *)
   scrollPane[expr_, size_] := 
    Framed[Pane[expr, Scrollbars -> Automatic, 
      AppearanceElements -> None, ImageSizeAction -> "Scrollable", 
      ImageMargins -> 0, FrameMargins -> 0, ImageSize -> size], 
     FrameStyle -> panel, ImageMargins -> 0, FrameMargins -> 0, 
     ImageSize -> size];
   divPane[n_] :=
    Deploy@EventHandler[MouseAppearance[Framed[
        Item[Button[Dynamic@If[state[[n]], First@icon, Last@icon],

          If[state[[n]], prev[[n]] = w; 
           w[[n]] = max - Sum[w[[i]], {i, n - 1}]; 
           Do[w[[i]] = 0, {i, n + 1, num}]; state[[n]] = False;, 
           w = prev[[n]]; state[[n]] = True;]
          , ContentPadding -> False, ImageSize -> sizeB, 
          FrameMargins -> 0, ImageMargins -> -1, 
          Appearance -> "Palette"], Alignment -> {Center, Center}]
        , ImageSize -> sizeD, FrameStyle -> None, ImageMargins -> 0, 
        FrameMargins -> 0, Background -> bg], mouse], 
      "MouseDown" :> onMouseDownCode@n, 
      "MouseDragged" :> onMouseDraggedCode@n, PassEventsDown -> True];
   onMouseDownCode[n_] := (
     old = {w[[n]], w[[n + 1]]};
     origo = coord@MousePosition@"CellContentsAbsolute";
     );
   onMouseDraggedCode[n_] := (
     temp = coord@MousePosition@"CellContentsAbsolute" - origo;
     w[[n]] = Min[Max[0, First@old + temp], Total@old];
     w[[n + 1]] = Total@old - w[[n]];
     );
   (* Framed is required below because it gives the expression \
margins. Otherwise, 
   if the scrollPane is set with larger than 0 FrameMargins, 
   they cannot be shrinked to zero width. *)
   grid[content_, size_] := 
    Riffle[MapThread[
      Dynamic[scrollPane[Framed[#1, FrameStyle -> None], size@#2], 
        TrackedSymbols :> {w}] &, {content, Range@Length@w}], 
     Dynamic[divPane@#, TrackedSymbols :> {w}] & /@ 
      Range@((Length@w) - 1)];

   Deploy@Grid[If[dir === "Vertical",
      List@grid[cont, {w[[#]], fix} &],
      List /@ grid[cont, {fix, w[[#]]} &]
      ], Spacings -> {0, -.1}, 
     ItemSize -> {{Table[0, {Length@w}]}, {Table[0, {Length@w}]}}],

   Initialization :> (
     (* w = width data list for all panels *)
     (* m = number of panels *)
     (* state = button states *)
     (* prev = previous state of w *)
     (* max = total width of all panels *)
     num = Length@w; state = True & /@ Range@num; 
     prev = w & /@ Range@num; max = Total@w;)
   ];
SplitPane[val_, 
    arg___] /; (Head@val === List \[And] And @@ (NumberQ /@ val)) := 
  Module[{x = val}, SplitPane[Dynamic@x, arg]];

让我们尝试一个垂直分割的窗格:

w = {200, 50, 100, 300};
SplitPane[
 Dynamic@w, {Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}],
   Null, CompleteGraph[5], "121234"}]

这是一个水平分割的窗格:

SplitPane[{50, 50, 50, 
  50}, {Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}, 
   ContentSize -> 300], Null, CompleteGraph[5], "121234"}, 
 Direction -> "Horizontal"]

垂直和水平窗格相结合:

xpane = {200, 300};
ypane = {200, 50};
SplitPane[Dynamic@xpane, {
  Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}],
  Dynamic[
   SplitPane[Dynamic@ypane, {CompleteGraph[5], "status"}, Last@xpane, 
    Paneled -> False, Direction -> "Horizontal"], 
   TrackedSymbols :> {xpane}]
  }, 300, Direction -> "Vertical"]

我想听听您对此解决方案的想法/cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 2012-04-18
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2016-09-17
    相关资源
    最近更新 更多