1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
|
#------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms described
# in the PyQt GPL exception also apply.
#
# Author: Riverbank Computing Limited
#------------------------------------------------------------------------------
"""Creates a panel-based PyQt user interface for a specified UI object.
"""
#-------------------------------------------------------------------------------
# Imports:
#-------------------------------------------------------------------------------
import cgi
import re
from pyface.qt import QtCore, QtGui
from traits.api \
import Any, Instance, Undefined
from traitsui.api \
import Group
from traits.trait_base \
import enumerate
from traitsui.undo \
import UndoHistory
from traitsui.help_template \
import help_template
from traitsui.menu \
import UndoButton, RevertButton, HelpButton
from helper \
import position_window
from ui_base \
import BasePanel
from editor \
import Editor
#-------------------------------------------------------------------------------
# Constants:
#-------------------------------------------------------------------------------
#: Characters that are considered punctuation symbols at the end of a label.
#: If a label ends with one of these charactes, we do not append a colon.
LABEL_PUNCTUATION_CHARS = '?=:;,.<>/\\"\'-+#|'
# Pattern of all digits
all_digits = re.compile(r'\d+')
#-------------------------------------------------------------------------------
# Create the different panel-based PyQt user interfaces.
#-------------------------------------------------------------------------------
def ui_panel(ui, parent):
"""Creates a panel-based PyQt user interface for a specified UI object.
"""
_ui_panel_for(ui, parent, False)
def ui_subpanel(ui, parent):
"""Creates a subpanel-based PyQt user interface for a specified UI object.
A subpanel does not allow control buttons (other than those specified in
the UI object) and does not show headers for view titles.
"""
_ui_panel_for(ui, parent, True)
def _ui_panel_for(ui, parent, is_subpanel):
"""Creates a panel-based PyQt user interface for a specified UI object.
"""
ui.control = control = _Panel(ui, parent, is_subpanel).control
control._parent = parent
control._object = ui.context.get('object')
control._ui = ui
try:
ui.prepare_ui()
except:
control.setParent(None)
del control
ui.control = None
ui.result = False
raise
ui.restore_prefs()
ui.result = True
class _Panel(BasePanel):
"""PyQt user interface panel for Traits-based user interfaces.
"""
def __init__(self, ui, parent, is_subpanel):
"""Initialise the object.
"""
self.ui = ui
history = ui.history
view = ui.view
# Reset any existing history listeners.
if history is not None:
history.on_trait_change(self._on_undoable, 'undoable', remove=True)
history.on_trait_change(self._on_redoable, 'redoable', remove=True)
history.on_trait_change(self._on_revertable, 'undoable',
remove=True)
# Determine if we need any buttons or an 'undo' history.
buttons = [self.coerce_button(button) for button in view.buttons]
nr_buttons = len(buttons)
has_buttons = (not is_subpanel and (nr_buttons != 1 or
not self.is_button(buttons[0], '')))
if nr_buttons == 0:
if view.undo:
self.check_button(buttons, UndoButton)
if view.revert:
self.check_button(buttons, RevertButton)
if view.help:
self.check_button(buttons, HelpButton)
if not is_subpanel and history is None:
for button in buttons:
if self.is_button(button, 'Undo') or self.is_button(button, 'Revert'):
history = ui.history = UndoHistory()
break
# Create the panel.
self.control = panel(ui)
# Suppress the title if this is a subpanel or if we think it should be
# superceded by the title of an "outer" widget (eg. a dock widget).
title = view.title
if (is_subpanel or (isinstance(parent, QtGui.QMainWindow) and
not isinstance(parent.parent(), QtGui.QDialog)) or
isinstance(parent, QtGui.QTabWidget)):
title = ""
# Panels must be widgets as it is only the TraitsUI PyQt code that can
# handle them being layouts as well. Therefore create a widget if the
# panel is not a widget or if we need a title or buttons.
if not isinstance(self.control, QtGui.QWidget) or title != "" or has_buttons:
w = QtGui.QWidget()
layout = QtGui.QVBoxLayout(w)
layout.setContentsMargins(0, 0, 0, 0)
# Handle any view title.
if title != "":
layout.addWidget(heading_text(None, text=view.title).control)
if isinstance(self.control, QtGui.QWidget):
layout.addWidget(self.control)
elif isinstance(self.control, QtGui.QLayout):
layout.addLayout(self.control)
self.control = w
# Add any buttons.
if has_buttons:
# Add the horizontal separator
separator = QtGui.QFrame()
separator.setFrameStyle(QtGui.QFrame.Sunken |
QtGui.QFrame.HLine)
separator.setFixedHeight(2)
layout.addWidget(separator)
# Add the special function buttons
bbox = QtGui.QDialogButtonBox(QtCore.Qt.Horizontal)
for button in buttons:
role = QtGui.QDialogButtonBox.ActionRole
if self.is_button(button, 'Undo'):
self.undo = self.add_button(button, bbox, role,
self._on_undo, False,
'Undo')
self.redo = self.add_button(button, bbox, role,
self._on_redo, False,
'Redo')
history.on_trait_change(self._on_undoable, 'undoable',
dispatch = 'ui')
history.on_trait_change(self._on_redoable, 'redoable',
dispatch = 'ui')
elif self.is_button(button, 'Revert'):
role = QtGui.QDialogButtonBox.ResetRole
self.revert = self.add_button(button, bbox, role,
self._on_revert, False)
history.on_trait_change(self._on_revertable, 'undoable',
dispatch = 'ui')
elif self.is_button(button, 'Help'):
role = QtGui.QDialogButtonBox.HelpRole
self.add_button(button, bbox, role, self._on_help)
elif not self.is_button(button, ''):
self.add_button(button, bbox, role)
layout.addWidget(bbox)
# Ensure the control has a size hint reflecting the View specification.
# Yes, this is a hack, but it's too late to repair this convoluted
# control building process, so we do what we have to...
self.control.sizeHint = _size_hint_wrapper(self.control.sizeHint, ui)
def panel(ui):
"""Creates a panel-based PyQt user interface for a specified UI object.
This function does not modify the UI object passed to it. The object
returned may be either a widget, a layout or None.
"""
# Bind the context values to the 'info' object:
ui.info.bind_context()
# Get the content that will be displayed in the user interface:
content = ui._groups
nr_groups = len(content)
if nr_groups == 0:
panel = None
if nr_groups == 1:
panel = _GroupPanel(content[0], ui).control
elif nr_groups > 1:
panel = QtGui.QTabWidget()
# Identify ourselves as being a Tabbed group so we can later
# distinguish this from other QTabWidgets.
panel.setProperty("traits_tabbed_group", True)
_fill_panel(panel, content, ui)
panel.ui = ui
# If the UI is scrollable then wrap the panel in a scroll area.
if ui.scrollable and panel is not None:
# Make sure the panel is a widget.
if isinstance(panel, QtGui.QLayout):
w = QtGui.QWidget()
w.setLayout(panel)
panel = w
sa = QtGui.QScrollArea()
sa.setWidget(panel)
sa.setWidgetResizable(True)
panel = sa
return panel
def _fill_panel(panel, content, ui, item_handler=None):
"""Fill a page based container panel with content.
"""
active = 0
for index, item in enumerate(content):
page_name = item.get_label(ui)
if page_name == "":
page_name = "Page %d" % index
if isinstance(item, Group):
if item.selected:
active = index
gp = _GroupPanel(item, ui, suppress_label=True)
page = gp.control
sub_page = gp.sub_control
# If the result is the same type with only one page, collapse it
# down into just the page.
if type(sub_page) is type(panel) and sub_page.count() == 1:
new = sub_page.widget(0)
if isinstance(panel, QtGui.QTabWidget):
sub_page.removeTab(0)
else:
sub_page.removeItem(0)
elif isinstance(page, QtGui.QWidget):
new = page
else:
new = QtGui.QWidget()
new.setLayout(page)
layout = new.layout()
if layout is not None:
layout.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
else:
new = QtGui.QWidget()
layout = QtGui.QVBoxLayout(new)
layout.setContentsMargins(0, 0, 0, 0)
item_handler(item, layout)
# Add the content.
if isinstance(panel, QtGui.QTabWidget):
panel.addTab(new, page_name)
else:
panel.addItem(new, page_name)
panel.setCurrentIndex(active)
def _size_hint_wrapper(f, ui):
"""Wrap an existing sizeHint method with sizes from a UI object.
"""
def sizeHint():
size = f()
if ui.view.width > 0:
size.setWidth(ui.view.width)
if ui.view.height > 0:
size.setHeight(ui.view.height)
return size
return sizeHint
#-------------------------------------------------------------------------------
# Displays a help window for the specified UI's active Group:
#-------------------------------------------------------------------------------
def show_help ( ui, button ):
""" Displays a help window for the specified UI's active Group.
"""
group = ui._groups[ ui._active_group ]
template = help_template()
if group.help != '':
header = template.group_help % cgi.escape( group.help )
else:
header = template.no_group_help
fields = []
for item in group.get_content( False ):
if not item.is_spacer():
fields.append( template.item_help % (
cgi.escape( item.get_label( ui ) ),
cgi.escape( item.get_help( ui ) ) ) )
html = template.group_html % ( header, '\n'.join( fields ) )
HTMLHelpWindow( button, html, .25, .33 )
#-------------------------------------------------------------------------------
# Displays a pop-up help window for a single trait:
#-------------------------------------------------------------------------------
def show_help_popup ( event ):
""" Displays a pop-up help window for a single trait.
"""
control = event.GetEventObject()
template = help_template()
# Note: The following check is necessary because under Linux, we get back
# a control which does not have the 'help' trait defined (it is the parent
# of the object with the 'help' trait):
help = getattr( control, 'help', None )
if help is not None:
html = template.item_html % ( control.GetLabel(), help )
HTMLHelpWindow( control, html, .25, .13 )
class _GroupSplitter(QtGui.QSplitter):
""" A splitter for a Traits UI Group with layout='split'.
"""
def __init__(self, group):
""" Store the group.
"""
QtGui.QSplitter.__init__(self)
self._group = group
self._initialized = False
def resizeEvent(self, event):
""" Overridden to position the splitter based on the Group when the
application is initializing.
Because the splitter layout algorithm requires that the available
space be known, we have to wait until the UI that contains this
splitter gives it its initial size.
"""
QtGui.QSplitter.resizeEvent(self, event)
parent = self.parent()
if (not self._initialized and parent and
(self.isVisible() or isinstance(parent, QtGui.QMainWindow))):
self._initialized = True
self._resize_items()
def showEvent(self, event):
""" Wait for the show event to resize items if necessary.
"""
QtGui.QSplitter.showEvent(self, event)
if not self._initialized:
self._initialized = True
self._resize_items()
def _resize_items(self):
""" Size the splitter based on the 'width' or 'height' attributes
of the Traits UI view elements.
"""
use_widths = (self.orientation() == QtCore.Qt.Horizontal)
# Get the requested size for the items.
sizes = []
for item in self._group.content:
if use_widths:
sizes.append(item.width)
else:
sizes.append(item.height)
# Find out how much space is available.
if use_widths:
total = self.width()
else:
total = self.height()
# Allocate requested space.
avail = total
remain = 0
for i, sz in enumerate(sizes):
if avail <= 0:
break
if sz >= 0:
if sz >= 1:
sz = min(sz, avail)
else:
sz *= total
sz = int(sz)
sizes[i] = sz
avail -= sz
else:
remain += 1
# Allocate the remainder to those parts that didn't request a width.
if remain > 0:
remain = int(avail / remain)
for i, sz in enumerate(sizes):
if sz < 0:
sizes[i] = remain
# If all requested a width, allocate the remainder to the last item.
else:
sizes[-1] += avail
self.setSizes(sizes)
class _GroupPanel(object):
"""A sub-panel for a single group of items. It may be either a layout or a
widget.
"""
def __init__(self, group, ui, suppress_label=False):
"""Initialise the object.
"""
# Get the contents of the group:
content = group.get_content()
# Save these for other methods.
self.group = group
self.ui = ui
if group.orientation == 'horizontal':
self.direction = QtGui.QBoxLayout.LeftToRight
else:
self.direction = QtGui.QBoxLayout.TopToBottom
# outer is the top-level widget or layout that will eventually be
# returned. sub is the QTabWidget or QToolBox corresponding to any
# 'tabbed' or 'fold' layout. It is only used to collapse nested
# widgets. inner is the object (not necessarily a layout) that new
# controls should be added to.
outer = sub = inner = None
# Get the group label.
if suppress_label:
label = ""
else:
label = group.label
# Create a border if requested.
if group.show_border:
outer = QtGui.QGroupBox(label)
inner = QtGui.QBoxLayout(self.direction, outer)
elif label != "":
outer = inner = QtGui.QBoxLayout(self.direction)
inner.addWidget(heading_text(None, text=label).control)
# Add the layout specific content.
if len(content) == 0:
pass
elif group.layout == 'flow':
raise NotImplementedError, "'the 'flow' layout isn't implemented"
elif group.layout == 'split':
# Create the splitter.
splitter = _GroupSplitter(group)
splitter.setOpaqueResize(False) # Mimic wx backend resize behavior
if self.direction == QtGui.QBoxLayout.TopToBottom:
splitter.setOrientation(QtCore.Qt.Vertical)
# Make sure the splitter will expand to fill available space
policy = splitter.sizePolicy()
policy.setHorizontalStretch(50)
policy.setVerticalStretch(50)
if group.orientation == 'horizontal':
policy.setVerticalPolicy(QtGui.QSizePolicy.Expanding)
else:
policy.setHorizontalPolicy(QtGui.QSizePolicy.Expanding)
splitter.setSizePolicy(policy)
if outer is None:
outer = splitter
else:
inner.addWidget(splitter)
# Create an editor.
editor = SplitterGroupEditor(control=outer, splitter=splitter,ui=ui)
self._setup_editor(group, editor)
self._add_splitter_items(content, splitter)
elif group.layout in ('tabbed', 'fold'):
# Create the TabWidget or ToolBox.
if group.layout == 'tabbed':
sub = QtGui.QTabWidget()
sub.setProperty("traits_tabbed_group", True)
else:
sub = QtGui.QToolBox()
# Give tab/tool widget stretch factor equivalent to default stretch
# factory for a resizeable item. See end of '_add_items'.
policy = sub.sizePolicy()
policy.setHorizontalStretch(50)
policy.setVerticalStretch(50)
sub.setSizePolicy(policy)
_fill_panel(sub, content, self.ui, self._add_page_item)
if outer is None:
outer = sub
else:
inner.addWidget(sub)
# Create an editor.
editor = TabbedFoldGroupEditor(container=sub, control=outer, ui=ui)
self._setup_editor(group, editor)
else:
# See if we need to control the visual appearance of the group.
if group.visible_when != '' or group.enabled_when != '':
# Make sure that outer is a widget and inner is a layout.
# Hiding a layout is not properly supported by Qt (the
# workaround in ``traitsui.qt4.editor._visible_changed_helper``
# often leaves undesirable blank space).
if outer is None:
outer = inner = QtGui.QBoxLayout(self.direction)
if isinstance(outer, QtGui.QLayout):
widget = QtGui.QWidget()
widget.setLayout(outer)
outer = widget
# Create an editor.
self._setup_editor(group, GroupEditor(control=outer))
if isinstance(content[0], Group):
layout = self._add_groups(content, inner)
else:
layout = self._add_items(content, inner)
layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
if outer is None:
outer = layout
elif layout is not inner:
inner.addLayout(layout)
if group.style_sheet :
if isinstance(outer, QtGui.QLayout) :
inner = outer
outer = QtGui.QWidget()
outer.setLayout(inner)
# ensure this is not empty group
if isinstance(outer, QtGui.QWidget) :
outer.setStyleSheet(group.style_sheet)
# Publish the top-level widget, layout or None.
self.control = outer
# Publish the optional sub-control.
self.sub_control = sub
def _add_splitter_items(self, content, splitter):
"""Adds a set of groups or items separated by splitter bars.
"""
for item in content:
# Get a panel for the Item or Group.
if isinstance(item, Group):
panel = _GroupPanel(item, self.ui, suppress_label=True).control
else:
panel = self._add_items([item])
# Add the panel to the splitter.
if panel is not None:
if isinstance(panel, QtGui.QLayout):
# A QSplitter needs a widget.
w = QtGui.QWidget()
panel.setContentsMargins(0, 0, 0, 0)
w.setLayout(panel)
panel = w
layout = panel.layout()
if layout is not None:
layout.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
splitter.addWidget(panel)
def _setup_editor(self, group, editor):
"""Setup the editor for a group.
"""
if group.id != '':
self.ui.info.bind(group.id, editor)
if group.visible_when != '':
self.ui.add_visible(group.visible_when, editor)
if group.enabled_when != '':
self.ui.add_enabled(group.enabled_when, editor)
def _add_page_item(self, item, layout):
"""Adds a single Item to a page based panel.
"""
self._add_items([item], layout)
def _add_groups(self, content, outer):
"""Adds a list of Group objects to the panel, creating a layout if
needed. Return the outermost layout.
"""
# Use the existing layout if there is one.
if outer is None:
outer = QtGui.QBoxLayout(self.direction)
# Process each group.
for subgroup in content:
panel = _GroupPanel(subgroup, self.ui).control
if isinstance(panel, QtGui.QWidget):
outer.addWidget(panel)
elif isinstance(panel, QtGui.QLayout):
outer.addLayout(panel)
else:
# The sub-group is empty which seems to be used as a way of
# providing some whitespace.
outer.addWidget(QtGui.QLabel(' '))
return outer
def _add_items(self, content, outer=None):
"""Adds a list of Item objects, creating a layout if needed. Return
the outermost layout.
"""
# Get local references to various objects we need:
ui = self.ui
info = ui.info
handler = ui.handler
group = self.group
show_left = group.show_left
columns = group.columns
# See if a label is needed.
show_labels = False
for item in content:
show_labels |= item.show_label
# See if a grid layout is needed.
if show_labels or columns > 1:
inner = QtGui.QGridLayout()
if outer is None:
outer = inner
else:
outer.addLayout(inner)
row = 0
if show_left:
label_alignment = QtCore.Qt.AlignRight
else:
label_alignment = QtCore.Qt.AlignLeft
else:
# Use the existing layout if there is one.
if outer is None:
outer = QtGui.QBoxLayout(self.direction)
inner = outer
row = -1
label_alignment = 0
# Process each Item in the list:
col = -1
for item in content:
# Keep a track of the current logical row and column unless the
# layout is not a grid.
col += 1
if row >= 0 and col >= columns:
col = 0
row += 1
# Get the name in order to determine its type:
name = item.name
# Check if is a label:
if name == '':
label = item.label
if label != "":
# Create the label widget.
if item.style == 'simple':
label = QtGui.QLabel(label)
else:
label = heading_text(None, text=label).control
self._add_widget(inner, label, row, col, show_labels)
if item.emphasized:
self._add_emphasis(label)
# Continue on to the next Item in the list:
continue
# Check if it is a separator:
if name == '_':
cols = columns
# See if the layout is a grid.
if row >= 0:
# Move to the start of the next row if necessary.
if col > 0:
col = 0
row += 1
# Skip the row we are about to do.
row += 1
# Allow for the columns.
if show_labels:
cols *= 2
for i in range(cols):
line = QtGui.QFrame()
if self.direction == QtGui.QBoxLayout.LeftToRight:
# Add a vertical separator:
line.setFrameShape(QtGui.QFrame.VLine)
if row < 0:
inner.addWidget(line)
else:
inner.addWidget(line, i, row)
else:
# Add a horizontal separator:
line.setFrameShape(QtGui.QFrame.HLine)
if row < 0:
inner.addWidget(line)
else:
inner.addWidget(line, row, i)
line.setFrameShadow(QtGui.QFrame.Sunken)
# Continue on to the next Item in the list:
continue
# Convert a blank to a 5 pixel spacer:
if name == ' ':
name = '5'
# Check if it is a spacer:
if all_digits.match( name ):
# If so, add the appropriate amount of space to the layout:
n = int( name )
if self.direction == QtGui.QBoxLayout.LeftToRight:
# Add a horizontal spacer:
spacer = QtGui.QSpacerItem(n, 1)
else:
# Add a vertical spacer:
spacer = QtGui.QSpacerItem(1, n)
self._add_widget(inner, spacer, row, col, show_labels)
# Continue on to the next Item in the list:
continue
# Otherwise, it must be a trait Item:
object = eval( item.object_, globals(), ui.context )
trait = object.base_trait( name )
desc = trait.desc or ''
# Get the editor factory associated with the Item:
editor_factory = item.editor
if editor_factory is None:
editor_factory = trait.get_editor().set(**item.editor_args)
# If still no editor factory found, use a default text editor:
if editor_factory is None:
from text_editor import ToolkitEditorFactory
editor_factory = ToolkitEditorFactory()
# If the item has formatting traits set them in the editor
# factory:
if item.format_func is not None:
editor_factory.format_func = item.format_func
if item.format_str != '':
editor_factory.format_str = item.format_str
# If the item has an invalid state extended trait name, set it
# in the editor factory:
if item.invalid != '':
editor_factory.invalid = item.invalid
# Create the requested type of editor from the editor factory:
factory_method = getattr( editor_factory, item.style + '_editor' )
editor = factory_method(
ui, object, name, item.tooltip, None
).set(item = item, object_name = item.object )
# Tell the editor to actually build the editing widget. Note that
# "inner" is a layout. This shouldn't matter as individual editors
# shouldn't be using it as a parent anyway. The important thing is
# that it is not None (otherwise the main TraitsUI code can change
# the "kind" of the created UI object).
editor.prepare(inner)
control = editor.control
if item.style_sheet :
control.setStyleSheet(item.style_sheet)
# Set the initial 'enabled' state of the editor from the factory:
editor.enabled = editor_factory.enabled
# Handle any label.
if item.show_label:
label = self._create_label(item, ui, desc)
self._add_widget(inner, label, row, col, show_labels,
label_alignment)
else:
label = None
editor.label_control = label
# Add emphasis to the editor control if requested:
if item.emphasized:
self._add_emphasis(control)
# Give the editor focus if it requested it:
if item.has_focus:
control.setFocus()
# Set the correct size on the control, as specified by the user:
stretch = 0
item_width = item.width
item_height = item.height
if (item_width != -1) or (item_height != -1):
is_horizontal = (self.direction == QtGui.QBoxLayout.LeftToRight)
min_size = control.minimumSizeHint()
width = min_size.width()
height = min_size.height()
force_width = False
force_height = False
if (0.0 < item_width <= 1.0) and is_horizontal:
stretch = int(100 * item_width)
item_width = int(item_width)
if item_width < -1:
item_width = -item_width
force_width = True
else:
item_width = max(item_width, width)
if (0.0 < item_height <= 1.0) and (not is_horizontal):
stretch = int(100 * item_height)
item_height = int(item_height)
if item_height < -1:
item_height = -item_height
force_height = True
else:
item_height = max(item_height, height)
control.setMinimumWidth(max(item_width, 0))
control.setMinimumHeight(max(item_height, 0))
if (stretch == 0 or not is_horizontal) and force_width :
control.setMaximumWidth(item_width)
if (stretch == 0 or is_horizontal) and force_height :
control.setMaximumHeight(item_height)
# Set size and stretch policies
self._set_item_size_policy(editor, item, label, stretch)
# Add the created editor control to the layout
# FIXME: Need to decide what to do about border_size and padding
self._add_widget(inner, control, row, col, show_labels)
# ---- Update the UI object
# Bind the editor into the UIInfo object name space so it can be
# referred to by a Handler while the user interface is active:
id = item.id or name
info.bind( id, editor, item.id )
self.ui._scrollable |= editor.scrollable
# Also, add the editors to the list of editors used to construct
# the user interface:
ui._editors.append( editor )
# If the handler wants to be notified when the editor is created,
# add it to the list of methods to be called when the UI is
# complete:
defined = getattr( handler, id + '_defined', None )
if defined is not None:
ui.add_defined( defined )
# If the editor is conditionally visible, add the visibility
# 'expression' and the editor to the UI object's list of monitored
# objects:
if item.visible_when != '':
ui.add_visible( item.visible_when, editor )
# If the editor is conditionally enabled, add the enabling
# 'expression' and the editor to the UI object's list of monitored
# objects:
if item.enabled_when != '':
ui.add_enabled( item.enabled_when, editor )
return outer
def _set_item_size_policy(self, editor, item, label, stretch):
""" Set size policy of an item and its label (if any).
How it is set:
1) The general rule is that we obey the item.resizable and
item.springy settings. An item is considered resizable also if
resizable is Undefined but the item is scrollable
2) However, if the labels are on the right, and the item is of a
kind that cannot be stretched in horizontal (e.g. a checkbox),
we make the label stretchable instead (to avoid big gaps
between element and label)
If the item is resizable, the _GroupPanel is set to be resizable.
"""
is_label_left = self.group.show_left
is_item_resizable = (
(item.resizable is True) or
((item.resizable is Undefined) and editor.scrollable)
)
is_item_springy = item.springy
# handle exceptional case 2)
item_policy = editor.control.sizePolicy().horizontalPolicy()
if (label is not None
and not is_label_left
and item_policy == QtGui.QSizePolicy.Minimum):
# this item cannot be stretched horizontally, and the label
# exists and is on the right -> make label stretchable if necessary
if (self.direction == QtGui.QBoxLayout.LeftToRight
and is_item_springy):
is_item_springy = False
self._make_label_h_stretchable(label, stretch or 50)
elif (self.direction == QtGui.QBoxLayout.TopToBottom
and is_item_resizable):
is_item_resizable = False
self._make_label_h_stretchable(label, stretch or 50)
if is_item_resizable:
stretch = stretch or 50
# FIXME: resizable is not defined as trait, were is it used?
self.resizable = True
elif is_item_springy:
stretch = stretch or 50
editor.set_size_policy(self.direction,
is_item_resizable, is_item_springy, stretch)
return stretch
def _make_label_h_stretchable(self, label, stretch):
""" Set size policies of a QLabel to be stretchable horizontally.
:attr:`stretch` is the stretch factor that Qt uses to distribute the
total size to individual elements
"""
label_policy = label.sizePolicy()
label_policy.setHorizontalStretch(stretch)
label_policy.setHorizontalPolicy(
QtGui.QSizePolicy.Expanding)
label.setSizePolicy(label_policy)
def _add_widget(self, layout, w, row, column, show_labels,
label_alignment=QtCore.Qt.AlignmentFlag(0)):
"""Adds a widget to a layout taking into account the orientation and
the position of any labels.
"""
# If the widget really is a widget then remove any margin so that it
# fills the cell.
if isinstance(w, QtGui.QWidget):
wl = w.layout()
if wl is not None:
wl.setContentsMargins(0, 0, 0, 0)
# See if the layout is a grid.
if row < 0:
if isinstance(w, QtGui.QWidget):
layout.addWidget(w)
elif isinstance(w, QtGui.QLayout):
layout.addLayout(w)
else:
layout.addItem(w)
else:
if self.direction == QtGui.QBoxLayout.LeftToRight:
# Flip the row and column.
row, column = column, row
if show_labels:
# Convert the "logical" column to a "physical" one.
column *= 2
# Determine whether to place widget on left or right of
# "logical" column.
if (label_alignment != 0 and not self.group.show_left) or \
(label_alignment == 0 and self.group.show_left):
column += 1
if isinstance(w, QtGui.QWidget):
layout.addWidget(w, row, column, label_alignment)
elif isinstance(w, QtGui.QLayout):
layout.addLayout(w, row, column, label_alignment)
else:
layout.addItem(w, row, column, 1, 1, label_alignment)
def _create_label(self, item, ui, desc, suffix=':'):
"""Creates an item label.
When the label is on the left of its component,
it is not empty, and it does not end with a
punctuation character (see :attr:`LABEL_PUNCTUATION_CHARS`),
we append a suffix (by default a colon ':') at the end of the
label text.
We also set the help on the QLabel control (from item.help) and
the tooltip (it item.desc exists; we add "Specifies " at the start
of the item.desc string).
Parameters
----------
item : Item
The item for which we want to create a label
ui : UI
Current ui object
desc : string
Description of the item, to create an appropriate tooltip
suffix : string
Characters to at the end of the label
Returns
-------
label_control : QLabel
The control for the label
"""
label = item.get_label(ui)
# append a suffix if the label is on the left and it does
# not already end with a punctuation character
if (label != ''
and label[-1] not in LABEL_PUNCTUATION_CHARS
and self.group.show_left):
label = label + suffix
# create label controller
label_control = QtGui.QLabel(label)
if item.emphasized:
self._add_emphasis(label_control)
# FIXME: Decide what to do about the help. (The non-standard wx way,
# What's This style help, both?)
#wx.EVT_LEFT_UP( control, show_help_popup )
label_control.help = item.get_help(ui)
# FIXME: do people rely on traitsui adding 'Specifies ' to the start
# of every tooltip? It's not flexible at all
if desc != '':
label_control.setToolTip('Specifies ' + desc)
return label_control
def _add_emphasis(self, control):
"""Adds emphasis to a specified control's font.
"""
# Set the foreground colour.
pal = QtGui.QPalette(control.palette())
pal.setColor(QtGui.QPalette.WindowText, QtGui.QColor(0, 0, 127))
control.setPalette(pal)
# Set the font.
font = QtGui.QFont(control.font())
font.setBold(True)
font.setPointSize(font.pointSize())
control.setFont(font)
class GroupEditor(Editor):
""" A pseudo-editor that allows a group to be managed.
"""
def __init__(self, **traits):
""" Initialise the object.
"""
self.set(**traits)
class SplitterGroupEditor(GroupEditor):
""" A pseudo-editor that allows a group with a 'split' layout to be managed.
"""
# The QSplitter for the group
splitter = Instance(_GroupSplitter)
#-- UI preference save/restore interface -----------------------------------
def restore_prefs(self, prefs):
""" Restores any saved user preference information associated with the
editor.
"""
if isinstance(prefs, dict):
structure = prefs.get('structure')
else:
structure = prefs
self.splitter._resized = True
self.splitter.restoreState(structure)
def save_prefs(self):
""" Returns any user preference information associated with the editor.
"""
return { 'structure': str(self.splitter.saveState()) }
class TabbedFoldGroupEditor(GroupEditor):
""" A pseudo-editor that allows a group with a 'tabbed' or 'fold' layout to
be managed.
"""
# The QTabWidget or QToolBox for the group
container = Any
#-- UI preference save/restore interface -----------------------------------
def restore_prefs(self, prefs):
""" Restores any saved user preference information associated with the
editor.
"""
if isinstance(prefs, dict):
current_index = prefs.get('current_index')
else:
current_index = prefs
self.container.setCurrentIndex(int(current_index))
def save_prefs(self):
""" Returns any user preference information associated with the editor.
"""
return { 'current_index': str(self.container.currentIndex()) }
#-------------------------------------------------------------------------------
# 'HTMLHelpWindow' class:
#-------------------------------------------------------------------------------
class HTMLHelpWindow ( QtGui.QDialog ):
""" Window for displaying Traits-based help text with HTML formatting.
"""
#---------------------------------------------------------------------------
# Initializes the object:
#---------------------------------------------------------------------------
def __init__ ( self, parent, html, scale_dx, scale_dy ):
""" Initializes the object.
"""
# Local import to avoid a WebKit dependency when one isn't needed.
from pyface.qt import QtWebKit
QtGui.QDialog.__init__(self, parent)
layout = QtGui.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
# Create the html control
html_control = QtWebKit.QWebView()
html_control.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
html_control.setHtml(html)
layout.addWidget(html_control)
# Create the OK button
bbox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok,
QtCore.Qt.Horizontal)
QtCore.QObject.connect(bbox, QtCore.SIGNAL('accepted()'),
self, QtCore.SLOT('accept()'))
layout.addWidget(bbox)
# Position and show the dialog
position_window(self, parent=parent)
self.show()
#-------------------------------------------------------------------------------
# Creates a PyFace HeadingText control:
#-------------------------------------------------------------------------------
HeadingText = None
def heading_text(*args, **kw):
"""Create a PyFace HeadingText control.
"""
global HeadingText
if HeadingText is None:
from pyface.api import HeadingText
return HeadingText(*args, **kw)
|