def __init__(self, parent=None): # This view is never made visible super(MetadataView, self).__init__() # A container for the controls self._form_container = FormContainer() # A scrollable container for the form self._form_scroll = QScrollArea(parent) self._form_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._form_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self._form_scroll.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self._form_scroll.setWidget(self._form_container) # Make the controls fill the available horizontal space # http://qt-project.org/forums/viewthread/11012 self._form_scroll.setWidgetResizable(True) # Title self._title = QLabel() # Title is fixed at the top - form can be scrolled layout = QVBoxLayout() layout.addWidget(self._title) layout.addWidget(self._form_scroll) # Top-level container for the title and form self.widget = QWidget(parent) self.widget.setLayout(layout)
def __init__( self, parent ): QScrollArea.__init__(self, parent) self.setFrameShape(QScrollArea.NoFrame) self.setAutoFillBackground(False) self.setWidgetResizable(True) self.setMouseTracking(True) #self.verticalScrollBar().setMaximumWidth(10) widget = QWidget(self) # define custom properties self._rolloutStyle = AccordionWidget.Rounded self._dragDropMode = AccordionWidget.NoDragDrop self._scrolling = False self._scrollInitY = 0 self._scrollInitVal = 0 self._itemClass = AccordionItem layout = QVBoxLayout() layout.setContentsMargins(2, 2, 2, 2) layout.setSpacing(2) layout.addStretch(1) widget.setLayout(layout) self.setWidget(widget)
def __init__(self, renderController, parent=None): super(RenderParameterWidget, self).__init__(parent=parent) self.renderController = renderController self.renderController.visualizationChanged.connect(self.visualizationLoaded) self.paramWidget = None self.visTypeComboBox = QComboBox() for visualizationType in self.renderController.visualizationTypes: self.visTypeComboBox.addItem(visualizationType) layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setSpacing(10) layout.setContentsMargins(10, 0, 10, 0) if len(self.renderController.visualizationTypes) > 1: layout.addWidget(QLabel("Visualization type:"), 0, 0) layout.addWidget(self.visTypeComboBox, 0, 1) self.setLayout(layout) self.scrollArea = QScrollArea() self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setAutoFillBackground(False) self.scrollArea.setAttribute(Qt.WA_TranslucentBackground) self.scrollArea.setWidgetResizable(True) self.visTypeComboBox.currentIndexChanged.connect(self.visTypeComboBoxChanged)
def generate_dialogs(self): vlayout = QVBoxLayout() commit_button = QPushButton("&Commit") w_all = QWidget() v = QVBoxLayout() for cell in self.plasm.cells(): tendril_widgets = [] for name, tendril in cell.params: if self.whitelist is None or self.is_in_whitelist( cell.name(), name): tw = TendrilWidget(name, tendril) commit_button.clicked.connect(tw.thunker.commit) tendril_widgets.append(tw) if tendril_widgets: w = QWidget() cvlayout = QVBoxLayout() cvlayout.addWidget(QLabel(cell.name())) for tendril_widget in tendril_widgets: cvlayout.addWidget(tendril_widget) w.setLayout(cvlayout) # w.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) v.addWidget(w) w_all.setLayout(v) s = QScrollArea() s.setWidget(w_all) vlayout.addWidget(s) vlayout.addWidget(commit_button) self.setLayout(vlayout)
def __init__(self): super(PointsWidget, self).__init__() self.landmarkWidgets = [] self.activeIndex = 0 self.scrollArea = QScrollArea(self) self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setAutoFillBackground(False) self.scrollArea.setAttribute(Qt.WA_TranslucentBackground) self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollArea.setWidgetResizable(True) landmarkLocationsLayout = QGridLayout() landmarkLocationsLayout.setSpacing(0) landmarkLocationsLayout.setContentsMargins(0, 0, 0, 0) landmarkLocationsLayout.setAlignment(Qt.AlignTop) self.landmarkLocationsWidget = QWidget() Style.styleWidgetForTab(self.landmarkLocationsWidget) self.landmarkLocationsWidget.setLayout(landmarkLocationsLayout) self.scrollArea.setWidget(self.landmarkLocationsWidget) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.scrollArea) self.setLayout(layout)
def _init_widgets(self): layout = QVBoxLayout() # address lbl_addr = QLabel() lbl_addr.setText("Address") txt_addr = QLineEdit() txt_addr.returnPressed.connect(self._on_address_entered) self._txt_addr = txt_addr top_layout = QHBoxLayout() top_layout.addWidget(lbl_addr) top_layout.addWidget(txt_addr) self._view = QMemoryView(self.workspace) area = QScrollArea() self._scrollarea = area area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setWidgetResizable(True) area.setWidget(self._view) layout.addLayout(top_layout) layout.addWidget(area) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout)
def init(self, parent): image = self.factory.image if image is None: image = self.value image_ctrl = myQLabel() if image is not None: image_ctrl.setPixmap(convert_bitmap(image)) self.image_ctrl = image_ctrl self.image_ctrl.setScaledContents(True) if self.factory.scrollable: scroll_area = QScrollArea() scroll_area.setWidget(image_ctrl) scroll_area.setWidgetResizable(True) scroll_area.setMinimumWidth(max(0, self.item.width)) scroll_area.setMinimumHeight(max(0, self.item.height)) self.control = scroll_area else: self.control = self.image_ctrl self.set_tooltip() self.sync_value(self.factory.refresh, 'refresh', 'from') self.update_editor()
def test_set_widget_succeeding(self): parent = QScrollArea() ChildAdder.add(QLabel(), 'fred', parent) self.assertTrue(isinstance(parent.widget(), QLabel)) # We promise to setWidgetResizable(True), also. resizable = parent.widgetResizable() self.assertTrue(resizable)
def __init__(self, parent=None): """Initialize Widget.""" super().__init__(parent) self.setLayout(QVBoxLayout()) self.imglabel = QLabel() self.imglabel.setBackgroundRole(QPalette.Base) self.imglabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.imglabel.setScaledContents(True) # Resize pixmap along with label self.imglabel.setAlignment(Qt.AlignCenter) self.imglabel.setText("(No image yet)") self.namelabel = QLabel() self.scrollarea = QScrollArea() self.scrollarea.setWidget(self.imglabel) self.scrollarea.setWidgetResizable(False) self.scrollarea.setAlignment(Qt.AlignCenter) self.layout().addWidget(self.scrollarea) self.layout().addWidget(self.namelabel) self.scale_factor = 1.0 self._initial_size = QSize(0, 0) self._img_path = "" self.setContextMenuPolicy(Qt.CustomContextMenu) # pylint: disable=no-member self.customContextMenuRequested.connect(self.show_context_menu) self.menu = QMenu() self.add_actions_to_menu(self.menu)
def generate_dialogs(self): vlayout = QVBoxLayout() commit_button = QPushButton("&Commit") w_all = QWidget() v = QVBoxLayout() for cell in self.plasm.cells(): tendril_widgets = [] for name, tendril in cell.params: if self.whitelist is None or self.is_in_whitelist(cell.name(), name): tw = TendrilWidget(name, tendril) commit_button.clicked.connect(tw.thunker.commit) tendril_widgets.append(tw) if tendril_widgets: w = QWidget() cvlayout = QVBoxLayout() cvlayout.addWidget(QLabel(cell.name())) for tendril_widget in tendril_widgets: cvlayout.addWidget(tendril_widget) w.setLayout(cvlayout) # w.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) v.addWidget(w) w_all.setLayout(v) s = QScrollArea() s.setWidget(w_all) vlayout.addWidget(s) vlayout.addWidget(commit_button) self.setLayout(vlayout)
def init(self, parent): image = self.factory.image if image is None: image = self.value image_ctrl = QLabel() # w = self.item.width # if self.factory.scale: # w *= self.factory.scale if image is not None: image_ctrl.setPixmap( convert_bitmap( image, # width=w, # height=self.item.height )) self.image_ctrl = image_ctrl # self.image_ctrl.setMinimumWidth(self.item.width) # self.image_ctrl.setMinimumHeight(self.item.height) if self.factory.scrollable: scroll_area = QScrollArea() scroll_area.setWidget(image_ctrl) scroll_area.setWidgetResizable(True) scroll_area.setMinimumWidth(self.item.width) scroll_area.setMinimumHeight(self.item.height) self.control = scroll_area else: self.control = self.image_ctrl self.set_tooltip() self.sync_value(self.factory.refresh, 'refresh', 'from')
def initUI(self): self.grid = QGridLayout() self.setLayout(self.grid) self.tree = TreeWidget(self, self.actionObjs, self.actionIDs, self.table) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.tree) if self.tree.rect().width() < 600: self.scrollArea.setFixedWidth(self.tree.rect().width() + 25) else: self.scrollArea.setFixedWidth(600) if self.tree.rect().height() < 600: self.scrollArea.setFixedHeight(self.tree.rect().height()) else: self.scrollArea.setFixedHeight(600) self.scrollArea.ensureWidgetVisible(self.tree, 500, 500) self.grid.addWidget(self.scrollArea, 0, 0, 10, 3) self.legend = Legend(self) self.grid.addWidget(self.legend, 0, 3, 1, 2) self.setWindowModality(Qt.ApplicationModal) self.show()
def create_scrolled_panel(self, parent): """ Returns a panel that can scroll its contents. """ sa = QScrollArea(check_parent(parent)) sa.setFrameShape(QFrame.NoFrame) sa.setWidgetResizable(True) return control_adapter_for(sa)
def __init__(self, parentQWidget=None): QScrollArea.__init__(self) self.mainView = MainView(self) self.setWidget(self.mainView) self.horizontalScrollBar().valueChanged.connect( self.mainView.setPositionHor) self.verticalScrollBar().valueChanged.connect( self.mainView.setPositionVer) self.resizeEvent = self.onResize
def _init_widgets(self): state = self._state if state is None: return if state.arch.name not in self.ARCH_REGISTERS: l.error( "Architecture %s is not listed in QRegisterViewer.ARCH_REGISTERS.", state.arch.name) return layout = QVBoxLayout() area = QScrollArea() area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setWidgetResizable(True) regs = self.ARCH_REGISTERS[state.arch.name] # common ones common_regs = regs['common'] for reg_name in common_regs: sublayout = QHBoxLayout() lbl_reg_name = QLabel(self) lbl_reg_name.setProperty('class', 'reg_viewer_label') lbl_reg_name.setText(reg_name) lbl_reg_name.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sublayout.addWidget(lbl_reg_name) sublayout.addSpacing(10) reg_value = QASTViewer(None, parent=self) self._registers[reg_name] = reg_value sublayout.addWidget(reg_value) layout.addLayout(sublayout) layout.setSpacing(0) layout.addStretch(0) layout.setContentsMargins(2, 2, 2, 2) # the container container = QFrame() container.setAutoFillBackground(True) palette = container.palette() palette.setColor(container.backgroundRole(), Qt.white) container.setPalette(palette) container.setLayout(layout) area.setWidget(container) base_layout = QVBoxLayout() base_layout.addWidget(area) self.setLayout(base_layout)
def createWidgets(self): self.fontLabel = QLabel("Fon&t:") self.fontComboBox = QFontComboBox() self.tooltips.append((self.fontComboBox, """\ <p><b>Font</b></p> <p>The font for displaying the characters.</p>""")) self.fontLabel.setBuddy(self.fontComboBox) self.sizeLabel = QLabel("&Size:") self.sizeComboBox = QComboBox() self.tooltips.append((self.sizeComboBox, """\ <p><b>Size</b></p> <p>The size of font for displaying the characters.</p>""")) self.sizeLabel.setBuddy(self.sizeComboBox) self.scrollArea = QScrollArea() self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.panel = Panel() self.scrollArea.setWidget(self.panel) self.copyTextLabel = QLabel("Copy T&ext") self.copyTextLineEdit = QLineEdit() self.tooltips.append((self.copyTextLineEdit, """\ <p><b>Copy Text editor</b></p> <p>The text for copying to the clipboard when <b>Copy</b> is pressed.</p>""")) self.copyTextLabel.setBuddy(self.copyTextLineEdit) self.findTextLabel = QLabel("&Find Text") self.findTextLineEdit = QLineEdit() self.tooltips.append((self.findTextLineEdit, """\ <p><b>Find Text editor</b></p> <p>The name or partial name of Unicode characters to be found, e.g., “star” will match many characters, including U+22C6 “Star operator”.</p>""")) self.findTextLabel.setBuddy(self.findTextLineEdit) self.buttonBox = QDialogButtonBox() self.addSelectedButton = QPushButton(QIcon(":/add.svg"), "&Add Selected") self.tooltips.append((self.addSelectedButton, """\ <p><b>Add Selected</b></p> <p>Append the selected character to the <b>Copy Text</b> editor.</p>""")) self.buttonBox.addButton(self.addSelectedButton, QDialogButtonBox.ActionRole) self.findNextButton = QPushButton(QIcon(":/edit-find.svg"), "Find &Next") self.tooltips.append((self.findNextButton, """\ <p><b>Find Next</b></p> <p>Find the next character whose Unicode name contains or equals the <b>Find Text</b>.</p>""")) self.buttonBox.addButton(self.findNextButton, QDialogButtonBox.ActionRole) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Copy Character dialog")) self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close") self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p> <p>Close the dialog.</p>""")) self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)
def addTab(self, tab, name, index=0): """Add the given tab to the TabDialog under the given name at the given index. The index 0 means the tab will be the active one when the TabDialog is raised. """ viewArea = QScrollArea() viewArea.setWidget(tab) viewArea.setWidgetResizable(True) self.tabs.insertTab(index, viewArea, name) self.tabs.setCurrentIndex(0)
def __init__(self): QScrollArea.__init__(self) self.mainWidget = QListWidget() self.setWidget(self.mainWidget) self.setWidgetResizable(True) self.setFixedWidth(200) self.setTitle()
def init(self, parent): image = self.factory.image if image is None: image = self.value image_ctrl = QLabel() # w = self.item.width # if self.factory.scale: # w *= self.factory.scale if image is not None: image_ctrl.setPixmap(convert_bitmap(image, # width=w, # height=self.item.height ) ) self.image_ctrl = image_ctrl # self.image_ctrl.setMinimumWidth(self.item.width) # self.image_ctrl.setMinimumHeight(self.item.height) if self.factory.scrollable: scroll_area = QScrollArea() scroll_area.setWidget(image_ctrl) scroll_area.setWidgetResizable(True) scroll_area.setMinimumWidth(self.item.width) scroll_area.setMinimumHeight(self.item.height) self.control = scroll_area else: self.control = self.image_ctrl self.set_tooltip() self.sync_value(self.factory.refresh, 'refresh', 'from')
def __init__(self, parent): QScrollArea.__init__(self) self.parent = parent self.mainWidget = QListWidget() self.setWidget(self.mainWidget) self.setWidgetResizable(True) self.setFixedHeight(130) self.setTitle()
def __init__(self): super(RenderInfoWidget, self).__init__() self.scrollArea = QScrollArea() self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setAutoFillBackground(False) self.scrollArea.setAttribute(Qt.WA_TranslucentBackground) self.scrollArea.setWidgetResizable(True) Style.styleWidgetForTab(self) Style.styleWidgetForTab(self.scrollArea)
def __init__(self, qpframe): QVBoxLayout.__init__(self) scroll = QScrollArea() scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(True) subWidget = QWidget() subWidget.setLayout(qpframe) scroll.setWidget(subWidget) self.addWidget(scroll) self.scroll = scroll
def init ( self, parent ): """ Finishes initializing the editor by creating the underlying toolkit widget. """ # Initialize the facet handler to use: facet_handler = self.factory.facet_handler if facet_handler is None: facet_handler = self.object.base_facet( self.name ).handler self._facet_handler = facet_handler # Create a scrolled window to hold all of the list item controls: self.control = QScrollArea( parent ) self.control.setFrameShape( QFrame.NoFrame ) # Create a widget with a grid layout as the container. self._list_pane = QWidget() layout = QGridLayout( self._list_pane ) layout.setMargin( 0 ) # Remember the editor to use for each individual list item: editor = self.factory.editor if editor is None: editor = facet_handler.item_facet.get_editor() self._editor = getattr( editor, self.kind ) # Set up the additional 'list items changed' event handler needed for # a list based facet: self.context_object.on_facet_set( self.update_editor_item, self.extended_name + '_items?', dispatch = 'ui' ) self.set_tooltip()
def _init_widgets(self): area = QScrollArea() area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setWidgetResizable(True) self._area = area base_layout = QVBoxLayout() base_layout.addWidget(area) self.setLayout(base_layout)
def __init__(self): super(CustomCircuitCreator, self).__init__() self.PaintArea = PaintArea(self) self.PaintArea.clearImage() self.grid = QGridLayout(self) self.grid.addWidget(self.PaintArea, 1, 0, 1, 9) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.createToolsButtons() self.createButtons() self.setWindowTitle("Custom circuit creator") self.resize(self.PaintArea.size_w, self.PaintArea.size_h + 85)
def initializeUI(self): self.mainWidget = QWidget() #Size self.resize(1024,768) #MenuBar menuBar = QMenuBar() self.fileMenu = DSPToolFileMenu(self) menuBar.addMenu(self.fileMenu) self.signalMenu = DSPToolSignalsMenu(self) menuBar.addMenu(self.signalMenu) self.setMenuBar(menuBar) #Table Widget self.table = QTableWidget() self.table.setFixedWidth(824) scrollTable = QScrollArea() scrollTable.setWidget(self.table) scrollTable.setWidgetResizable(True) #Side and Property Bar self.sideBar = SideBar() self.propertyBar = PropertyBar(self) #Layouts hLayout = QHBoxLayout() hLayout.addWidget(self.table) hLayout.addWidget(self.sideBar) hWidget = QWidget() hWidget.setLayout(hLayout) vLayout = QVBoxLayout() vLayout.addWidget(hWidget) vLayout.addWidget(self.propertyBar) self.mainWidget.setLayout(vLayout) self.setCentralWidget(self.mainWidget) #Signals self.table.cellClicked.connect(self.oneClickedEvent)
def generate_dialogs(self): vlayout = QVBoxLayout() commit_button = QPushButton("&Commit") w_all = QWidget() v = QVBoxLayout() for cell in self.plasm.cells(): w = QWidget() cvlayout = QVBoxLayout() cvlayout.addWidget(QLabel(cell.name())) for name, tendril in cell.params: tw = TendrilWidget(name, tendril) cvlayout.addWidget(tw) commit_button.clicked.connect(tw.thunker.commit) w.setLayout(cvlayout) # w.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) v.addWidget(w) w_all.setLayout(v) s = QScrollArea() s.setWidget(w_all) vlayout.addWidget(s) vlayout.addWidget(commit_button) self.setLayout(vlayout)
def __init__(self): QMainWindow.__init__(self) self.project = None menuBar = QMenuBar() self.fileMenu = DSPToolFileMenu(self) menuBar.addMenu(self.fileMenu) self.signalMenu = DSPToolSignalsMenu(self) menuBar.addMenu(self.signalMenu) self.setMenuBar(menuBar) self.mainWidget=QTableWidget() self.mainWidget.setRowCount(0) self.mainWidget.setColumnCount(0) scrollWidget = QScrollArea() scrollWidget.setWidget(self.mainWidget) scrollWidget.setWidgetResizable(True) self.setCentralWidget(scrollWidget)
def add_command_tab(self, command_list, tab_name = "Commands"): outer_widget = QWidget() outer_layout = QVBoxLayout() outer_widget.setLayout(outer_layout) outer_layout.setContentsMargins(2, 2, 2, 2) outer_layout.setSpacing(1) for c in command_list: new_command = qButtonWithArgumentsClass(c[1], c[0], c[2], self.help_instance, max_field_size = 100) outer_layout.addWidget(new_command) outer_layout.setAlignment(new_command,QtCore.Qt.AlignTop ) outer_layout.addStretch() scroller = QScrollArea() scroller.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # scroller.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroller.setWidget(outer_widget) scroller.setWidgetResizable(True) self.addTab(scroller, tab_name)
def __init__(self, *args, **kwargs): super(Dialog_deleteUnused, self).__init__(*args, **kwargs) self.installEventFilter(self) self.setObjectName(Dialog_deleteUnused.objectName) self.setWindowTitle(Dialog_deleteUnused.title) self.resize(Dialog_deleteUnused.defaultWidth, Dialog_deleteUnused.defaultHeight) mainLayout = QVBoxLayout(self) label_download = QLabel( "The following files will be deleted. Continue?".decode('utf-8')) label_download.setMaximumHeight(30) scrollArea = QScrollArea() fileList = QListWidget() scrollArea.setWidget(fileList) scrollArea.setWidgetResizable(True) hLayout_buttons = QHBoxLayout() button_delete = QPushButton("Delete All".decode('utf-8')) button_cancel = QPushButton("Cancel".decode('utf-8')) hLayout_buttons.addWidget(button_delete) hLayout_buttons.addWidget(button_cancel) mainLayout.addWidget(label_download) mainLayout.addWidget(scrollArea) mainLayout.addLayout(hLayout_buttons) self.fileList = fileList self.button_delete = button_delete QtCore.QObject.connect(button_delete, QtCore.SIGNAL('clicked()'), self.cmd_deleteSelected) QtCore.QObject.connect(button_cancel, QtCore.SIGNAL('clicked()'), self.cmd_cancel) QtCore.QObject.connect(self.fileList, QtCore.SIGNAL("itemSelectionChanged()"), self.cmd_setButtonCondition) self.fileList.setSelectionMode(QAbstractItemView.ExtendedSelection)
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) self.setWindowTitle("Copy Character — {}".format( QApplication.applicationName())) QShortcut(QKeySequence(QKeySequence.FindNext), self, self.findNext) self.state = state self.createWidgets() self.layoutWidgets() self.createConnections() self.findSizes(self.fontComboBox.currentFont()) self.setToFamily(self.state.stdFontFamily) self.setToNearestSize(self.state.stdFontSize) settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.fontLabel = QLabel("Fon&t:") self.fontComboBox = QFontComboBox() self.tooltips.append((self.fontComboBox, """\ <p><b>Font</b></p> <p>The font for displaying the characters.</p>""")) self.fontLabel.setBuddy(self.fontComboBox) self.sizeLabel = QLabel("&Size:") self.sizeComboBox = QComboBox() self.tooltips.append((self.sizeComboBox, """\ <p><b>Size</b></p> <p>The size of font for displaying the characters.</p>""")) self.sizeLabel.setBuddy(self.sizeComboBox) self.scrollArea = QScrollArea() self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.panel = Panel() self.scrollArea.setWidget(self.panel) self.copyTextLabel = QLabel("Copy T&ext") self.copyTextLineEdit = QLineEdit() self.tooltips.append((self.copyTextLineEdit, """\ <p><b>Copy Text editor</b></p> <p>The text for copying to the clipboard when <b>Copy</b> is pressed.</p>""")) self.copyTextLabel.setBuddy(self.copyTextLineEdit) self.findTextLabel = QLabel("&Find Text") self.findTextLineEdit = QLineEdit() self.tooltips.append((self.findTextLineEdit, """\ <p><b>Find Text editor</b></p> <p>The name or partial name of Unicode characters to be found, e.g., “star” will match many characters, including U+22C6 “Star operator”.</p>""")) self.findTextLabel.setBuddy(self.findTextLineEdit) self.buttonBox = QDialogButtonBox() self.addSelectedButton = QPushButton(QIcon(":/add.svg"), "&Add Selected") self.tooltips.append((self.addSelectedButton, """\ <p><b>Add Selected</b></p> <p>Append the selected character to the <b>Copy Text</b> editor.</p>""")) self.buttonBox.addButton(self.addSelectedButton, QDialogButtonBox.ActionRole) self.findNextButton = QPushButton(QIcon(":/edit-find.svg"), "Find &Next") self.tooltips.append((self.findNextButton, """\ <p><b>Find Next</b></p> <p>Find the next character whose Unicode name contains or equals the <b>Find Text</b>.</p>""")) self.buttonBox.addButton(self.findNextButton, QDialogButtonBox.ActionRole) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Copy Character dialog")) self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close") self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p> <p>Close the dialog.</p>""")) self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) def layoutWidgets(self): topLayout = QHBoxLayout() topLayout.addWidget(self.fontLabel) topLayout.addWidget(self.fontComboBox, 1) topLayout.addWidget(self.sizeLabel) topLayout.addWidget(self.sizeComboBox) bottomLayout = QHBoxLayout() bottomLayout.addWidget(self.copyTextLabel) bottomLayout.addWidget(self.copyTextLineEdit) bottomLayout.addWidget(self.findTextLabel) bottomLayout.addWidget(self.findTextLineEdit) layout = QVBoxLayout() layout.addLayout(topLayout) layout.addWidget(self.scrollArea, 1) layout.addLayout(bottomLayout) layout.addWidget(self.buttonBox) self.setLayout(layout) def createConnections(self): self.fontComboBox.activated[str].connect(self.panel.updateFont) self.sizeComboBox.currentIndexChanged[str].connect( self.panel.updateSize) self.panel.characterSelected.connect(self.copyTextLineEdit.insert) self.panel.fontResized.connect(self.updateSize) self.addSelectedButton.clicked.connect(self.addSelected) self.helpButton.clicked.connect(self.help) self.buttonBox.rejected.connect(self.accept) self.findNextButton.clicked.connect(self.findNext) self.findTextLineEdit.returnPressed.connect(self.findNext) def help(self): self.state.help("xix_ref_dlg_copychr.html") def findSizes(self, font): fontDatabase = QFontDatabase() currentSize = self.sizeComboBox.currentText() with Lib.BlockSignals(self.sizeComboBox): self.sizeComboBox.clear() if fontDatabase.isSmoothlyScalable(font.family(), fontDatabase.styleString(font)): for size in QFontDatabase.standardSizes(): self.sizeComboBox.addItem(str(size)) else: for size in fontDatabase.smoothSizes( font.family(), fontDatabase.styleString(font)): self.sizeComboBox.addItem(str(size)) self.sizeComboBox.setEditable(False) sizeIndex = self.sizeComboBox.findText(currentSize) if sizeIndex == -1: self.sizeComboBox.setCurrentIndex( max(0, self.sizeComboBox.count() / 3)) else: self.sizeComboBox.setCurrentIndex(sizeIndex) def accept(self): clipboard = QApplication.clipboard() text = self.copyTextLineEdit.text() or self.panel.currentChar clipboard.setText(text, QClipboard.Clipboard) clipboard.setText(text, QClipboard.Selection) if text: say("Copied “{}” to the clipboard".format(text), SAY_TIMEOUT) super().accept() def addSelected(self): char = self.panel.currentChar if char: self.copyTextLineEdit.setText(self.copyTextLineEdit.text() + char) self.findNextButton.setFocus() def setToFamily(self, family): family = family.casefold() for i in range(self.fontComboBox.count()): if self.fontComboBox.itemText(i).casefold() == family: self.fontComboBox.setCurrentIndex(i) break def setToNearestSize(self, size): below = 0 belowIndex = -1 above = 999 aboveIndex = -1 for i in range(self.sizeComboBox.count()): sz = int(self.sizeComboBox.itemText(i)) if sz == size: self.sizeComboBox.setCurrentIndex(i) break if sz < size and sz > below: below = sz belowIndex = i if sz > size and sz < above: above = sz aboveIndex = i else: if abs(size - below) < abs(size - above): self.sizeComboBox.setCurrentIndex(belowIndex) else: self.sizeComboBox.setCurrentIndex(aboveIndex) def findNext(self): text = self.findTextLineEdit.text().strip().casefold() if text: start = self.panel.currentChar start = ord(start) if start else ord(" ") for i in range(start + 1, MAX_CHAR): try: char = chr(i) name = unicodedata.name(char).casefold() if text in name: self.panel.currentChar = char self.panel.update() y = (self.panel.squareSize * i) // COLUMNS self.scrollArea.ensureVisible(0, y) break except ValueError: pass else: self.panel.currentChar = " " self.findNext() def keyPressEvent(self, event): key = event.key() if key in {Qt.Key_Enter, Qt.Key_Return}: if self.findTextLineEdit.text().strip(): self.findNext() else: self.addSelectedButton.setFocus() def updateSize(self, squareSize): self.setMinimumWidth((COLUMNS + (1.5 if WIN else 1)) * squareSize)
def setup(self): self.dirty = False self.def_cfg = copy.deepcopy(self.config) self.config.update_from_user_file() self.base_cfg = copy.deepcopy(self.config) self.categories = QListWidget() #self.categories.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Expanding) self.settings = QStackedWidget() #self.categories.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.Expanding) QObject.connect(self.categories, SIGNAL('itemSelectionChanged()'), self.category_selected) self.widget_list = {} for cat in self.config.get_categories(): self.widget_list[cat] = {} longest_cat = 0 for cat in self.config.get_categories(): if len(cat) > longest_cat: longest_cat = len(cat) self.categories.addItem(cat) settings_layout = QGridLayout() r = 0 c = 0 for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) s = QWidget() s.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) sl = QVBoxLayout() label = QLabel() if info.has_key('alias'): label.setText(info['alias']) else: label.setText(setting) if info.has_key('about'): label.setToolTip(info['about']) sl.addWidget(label) if info['type'] == constants.CT_LINEEDIT: w = LineEdit(self, self.config,cat,setting,info) elif info['type'] == constants.CT_CHECKBOX: w = CheckBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_SPINBOX: w = SpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_DBLSPINBOX: w = DoubleSpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_COMBO: w = ComboBox(self, self.config,cat,setting,info) w.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) self.widget_list[cat][setting] = w sl.addWidget(w) s.setLayout(sl) c = self.config.config[cat].index(setting) % 2 settings_layout.addWidget(s, r, c) if c == 1: r += 1 settings = QWidget() settings.setLayout(settings_layout) settings_scroller = QScrollArea() settings_scroller.setWidget(settings) settings_scroller.setWidgetResizable(True) self.settings.addWidget(settings_scroller) font = self.categories.font() fm = QFontMetrics(font) self.categories.setMaximumWidth(fm.widthChar('X')*(longest_cat+4)) self.main = QWidget() self.main_layout = QVBoxLayout() self.config_layout = QHBoxLayout() self.config_layout.addWidget(self.categories) self.config_layout.addWidget(self.settings) self.mainButtons = QDialogButtonBox(QDialogButtonBox.RestoreDefaults | QDialogButtonBox.Reset | QDialogButtonBox.Apply) self.main_apply = self.mainButtons.button(QDialogButtonBox.StandardButton.Apply) self.main_reset = self.mainButtons.button(QDialogButtonBox.StandardButton.Reset) self.main_defaults = self.mainButtons.button(QDialogButtonBox.StandardButton.LastButton) QObject.connect(self.mainButtons, SIGNAL('clicked(QAbstractButton *)'), self.mainbutton_clicked) self.dirty_check() self.main_layout.addLayout(self.config_layout) self.main_layout.addWidget(self.mainButtons) self.main.setLayout(self.main_layout) self.setCentralWidget(self.main) self.setWindowTitle(self.title) self.setUnifiedTitleAndToolBarOnMac(True) self.categories.setCurrentItem(self.categories.item(0)) self.menuBar = QMenuBar() self.filemenu = QMenu('&File') self.quitAction = QAction(self) self.quitAction.setText('&Quit') if platform.system() != 'Darwin': self.quitAction.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q)) QObject.connect(self.quitAction, SIGNAL('triggered()'), self.quitApp) self.filemenu.addAction(self.quitAction) self.menuBar.addMenu(self.filemenu) self.setMenuBar(self.menuBar) self.show() self.activateWindow() self.raise_() self.setMinimumWidth(self.geometry().width()*1.2) screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
class MetadataView(QAbstractItemView): MESSAGE_NO_SELECTION = 'Metadata' MESSAGE_SINGLE_SELECTION = 'Metadata for 1 box' MESSAGE_MULTIPLE_SELECTION = 'Metadata for {0} boxes' def __init__(self, parent=None): # This view is never made visible super(MetadataView, self).__init__() # A container for the controls self._form_container = FormContainer() # A scrollable container for the form self._form_scroll = QScrollArea(parent) self._form_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._form_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self._form_scroll.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self._form_scroll.setWidget(self._form_container) # Make the controls fill the available horizontal space # http://qt-project.org/forums/viewthread/11012 self._form_scroll.setWidgetResizable(True) # Title self._title = QLabel() # Title is fixed at the top - form can be scrolled layout = QVBoxLayout() layout.addWidget(self._title) layout.addWidget(self._form_scroll) # Top-level container for the title and form self.widget = QWidget(parent) self.widget.setLayout(layout) def reset(self): """QAbstractItemView virtual """ debug_print('MetadataView.reset') super(MetadataView, self).reset() # Clear the controls self.selectionChanged([], []) def selectionChanged(self, selected, deselected): """QAbstractItemView slot """ debug_print('MetadataView.selectionChanged') selected = self.selectionModel().selectedIndexes() # Set title if 1 == len(selected): title = self.MESSAGE_SINGLE_SELECTION elif selected: title = self.MESSAGE_MULTIPLE_SELECTION.format(len(selected)) else: title = self.MESSAGE_NO_SELECTION self._title.setText(title) # TODO Combo should indicate multiple and unrecognised values # Put values into the controls metadata = [i.data(MetadataRole) for i in selected] for field, control in self._form_container.controls.iteritems(): values = {m.get(field, '') for m in metadata} control.selection_changed(selected, values)
def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setGeometry(0, 0, 1500, 1000) self.move( QApplication.desktop().screenGeometry().center() - self.rect().center()) self.show() # Main layout self.layout = QHBoxLayout() self.setLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) titles = odict([ ["Presets", odict([["preset", "Presets"]])], ["Cosmological Model", odict([ ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Hubble parameter constraint"], ["matter", "Matter sector"], ["neutrinos", "Neutrinos and other extra matter"], ["dark_energy", "Lambda / Dark energy"], ["bbn", "BBN"], ["reionization", "Reionization history"]])], ["Data sets", odict([ ["like_cmb", "CMB experiments"], ["like_bao", "BAO experiments"], ["like_sn", "SN experiments"], ["like_H0", "Local H0 measurements"]])], ["Sampler", odict([["sampler", "Samplers"]])]]) self.combos = odict() for group, fields in titles.items(): group_box = QGroupBox(group) self.layout_options.addWidget(group_box) group_layout = QVBoxLayout(group_box) for a, desc in fields.items(): self.combos[a] = QComboBox() if len(fields) > 1: label = QLabel(desc) group_layout.addWidget(label) group_layout.addWidget(self.combos[a]) self.combos[a].addItems( [text(k, v) for k, v in getattr(input_database, a).items()]) # PLANCK NAMES CHECKBOX TEMPORARILY DISABLED # if a == "theory": # # Add Planck-naming checkbox # self.planck_names = QCheckBox( # "Keep common parameter names " # "(useful for fast CLASS/CAMB switching)") # group_layout.addWidget(self.planck_names) # Connect to refreshers -- needs to be after adding all elements for field, combo in self.combos.items(): if field == "preset": combo.currentIndexChanged.connect(self.refresh_preset) else: combo.currentIndexChanged.connect(self.refresh) # self.planck_names.stateChanged.connect(self.refresh_keep_preset) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python", "citations"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)
class UserDetailsWindow(UberSquareWindow): def __init__(self, user, parent): super(UserDetailsWindow, self).__init__(parent) self.user = user self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(11, 11, 11, 11) self.centralWidget.setLayout(layout) self.container = QWidget() self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.container) self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) layout.addWidget(self.scrollArea) self.scrollArea.setWidgetResizable(True) gridLayout = QGridLayout() self.container.setLayout(gridLayout) firstName = user['user']['firstName'] name = firstName if 'lastName' in user['user']: name += " " + user['user']['lastName'] self.setWindowTitle(name) photo_label = QLabel() photo = QImage(foursquare.image(self.user['user']['photo'])) photo_label.setPixmap(QPixmap(photo)) i = 0 gridLayout.addWidget(UserProfile(user), i, 0, 1, 2) ### checkin button if user['user']['relationship'] != "self": i += 1 self.shoutText = QLineEdit(self) self.shoutText.setPlaceholderText("Shout something") gridLayout.addWidget(self.shoutText, i, 0) checkinButton = QPushButton("Check-in with " + firstName) self.connect(checkinButton, SIGNAL("clicked()"), self.checkin) gridLayout.addWidget(checkinButton, i, 1) # TODO! #if user['user']['relationship'] == "friend": # i += 1 # gridLayout.addWidget(QLabel("TODO: Unfriend"), i, 0, 1, 2) elif user['user']['relationship'] == "self": i += 1 gridLayout.addWidget(QLabel("It's you!"), i, 0, 1, 2) if user['user']['id'] == "17270875": i += 1 gridLayout.addWidget(QLabel("<b>This is the UberSquare developer!</b>"), i, 0, 1, 2) i += 1 checkins = user['user']['checkins']['count'] gridLayout.addWidget(QLabel(str(checkins) + " checkins"), i, 0) i += 1 badges = user['user']['badges']['count'] gridLayout.addWidget(QLabel(str(badges) + " badges"), i, 0) i += 1 mayorships = user['user']['mayorships']['count'] if mayorships > 0: mayorshipsButton = QPushButton(str(mayorships) + " mayorships") mayorshipsButton.setIcon(QIcon(foursquare.image("https://foursquare.com/img/points/mayor.png"))) self.connect(mayorshipsButton, SIGNAL("clicked()"), self.mayorships_pushed) gridLayout.addWidget(mayorshipsButton, i, 0, 1, 2) else: gridLayout.addWidget(QLabel("No mayorships"), i, 0) i += 1 # TODO! #gridLayout.addWidget(QPushButton("TODO: See places " + firstName + " has been to."), i, 0, 1, 2) #i += 1 update_user_button = QPushButton("Refresh user details") update_user_button.setIcon(QIcon.fromTheme("general_refresh")) self.connect(update_user_button, SIGNAL("clicked()"), self.__update) gridLayout.addWidget(update_user_button, i, 0, 1, 2) showUser = Signal() self.connect(self, SIGNAL("showUser()"), self.__showUser) def __update(self): print "updating..." t = UserDetailsThread(self.user['user']['id'], self) t.start() self.showWaitingDialog.emit() def __showUser(self): time.sleep(0.15) self.close() self.uid = self.user['user']['id'] user = foursquare.get_user(self.uid, foursquare.CacheOrNull) if user: self.userWindow = UserDetailsWindow(user, self) self.userWindow.show() def checkin(self): venue = self.user['user']['checkins']['items'][0]['venue'] c = CheckinConfirmation(self, venue) c.exec_() if c.result() == QDialog.Accepted: try: # TODO: do this in a separate thread ll = LocationProvider().get_ll(venue) response = foursquare.checkin(venue, ll, self.shoutText.text(), c.broadcast()) CheckinDetails(self, response).show() except IOError: self.networkError.emit() def mayorships_pushed(self): # TODO: show user's name venueListWindow = VenueListWindow("Mayorships", None, self) dataSource = UserMayorships(venueListWindow, self.user['user']['id'], self) venues = dataSource.getVenues(foursquare.Cache.CacheOrNull) dataSource.start() if venues: self.setVenues(venues) venueListWindow.updateVenues.emit() else: self.showWaitingDialog.emit() def setVenues(self, venues): self.__venues = venues def venues(self): return self.__venues
def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setGeometry(0, 0, 1500, 1000) self.move( QApplication.desktop().screen().rect().center() - self.rect().center()) self.show() # Main layout self.layout = QHBoxLayout() self.setLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) self.atoms = odict() titles = odict([ ["preset", "Presets"], ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Constaint on hubble parameter"], ["baryons", "Baryon sector"], ["dark_matter", "Dark matter"], ["dark_energy", "Lambda / Dark energy"], ["neutrinos", "Neutrinos and other extra matter"], ["bbn", "BBN"], ["reionization", "Reionization history"], ["cmb_lensing", "CMB lensing"], ["cmb", "CMB experiments"], ["sampler", "Samplers"]]) for a in titles: self.atoms[a] = { "group": QGroupBox(titles[a]), "combo": QComboBox()} self.layout_options.addWidget(self.atoms[a]["group"]) self.atoms[a]["layout"] = QVBoxLayout(self.atoms[a]["group"]) self.atoms[a]["layout"].addWidget(self.atoms[a]["combo"]) self.atoms[a]["combo"].addItems( [text(k,v) for k,v in getattr(input_database, a).items()]) # Connect to refreshers -- needs to be after adding all elements for a in self.atoms: if a == "preset": self.atoms["preset"]["combo"].currentIndexChanged.connect( self.refresh_preset) continue self.atoms[a]["combo"].currentIndexChanged.connect(self.refresh) # Add Planck-naming checkbox and connect to refresher too self.planck_names = QCheckBox("Keep common names") self.atoms["theory"]["layout"].addWidget(self.planck_names) self.planck_names.stateChanged.connect(self.refresh) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)
def initUI(self): hbox = QtGui.QHBoxLayout(self) first = QtGui.QFrame(self) first.setFrameShape(QtGui.QFrame.StyledPanel) scrollAreaLeft = QScrollArea() scrollAreaLeft.setWidgetResizable(True) scrollAreaLeft.setWidget(first) second = QtGui.QFrame(self) second.setFrameShape(QtGui.QFrame.StyledPanel) scrollAreaRight = QScrollArea() scrollAreaRight.setWidgetResizable(True) scrollAreaRight.setWidget(second) splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) splitter.addWidget(scrollAreaLeft) splitter.addWidget(scrollAreaRight) splitter.setSizes([10, 100]) hbox.addWidget(splitter) self.setLayout(hbox) self.setGeometry(600, 600, 600, 600) self.setWindowTitle('QtGui.QSplitter') self.show() print("scrollAreaLeft width: " + str(scrollAreaLeft.width())) print("scrollAreaRight width: " + str(scrollAreaRight.width()))
class SimpleEditor ( Editor ): """ Simple style of editor for lists, which displays a scrolling list box with only one item visible at a time. A icon next to the list box displays a menu of operations on the list. """ #-- Class Constants -------------------------------------------------------- # Whether the list is displayed in a single row: single_row = True # Menu for modifying the list list_menu = """ Add &Before [_menu_before]: self.add_before() Add &After [_menu_after]: self.add_after() --- &Delete [_menu_delete]: self.delete_item() --- Move &Up [_menu_up]: self.move_up() Move &Down [_menu_down]: self.move_down() Move to &Top [_menu_top]: self.move_top() Move to &Bottom [_menu_bottom]: self.move_bottom() """ empty_list_menu = """ Add: self.add_empty() """ #-- Facet Definitions ------------------------------------------------------ # The kind of editor to create for each list item: kind = Str # Is the list of items being edited mutable? mutable = Bool( True ) #-- Public Methods --------------------------------------------------------- def init ( self, parent ): """ Finishes initializing the editor by creating the underlying toolkit widget. """ # Initialize the facet handler to use: facet_handler = self.factory.facet_handler if facet_handler is None: facet_handler = self.object.base_facet( self.name ).handler self._facet_handler = facet_handler # Create a scrolled window to hold all of the list item controls: self.control = QScrollArea( parent ) self.control.setFrameShape( QFrame.NoFrame ) # Create a widget with a grid layout as the container. self._list_pane = QWidget() layout = QGridLayout( self._list_pane ) layout.setMargin( 0 ) # Remember the editor to use for each individual list item: editor = self.factory.editor if editor is None: editor = facet_handler.item_facet.get_editor() self._editor = getattr( editor, self.kind ) # Set up the additional 'list items changed' event handler needed for # a list based facet: self.context_object.on_facet_set( self.update_editor_item, self.extended_name + '_items?', dispatch = 'ui' ) self.set_tooltip() def dispose ( self ): """ Disposes of the contents of an editor. """ self.context_object.on_facet_set( self.update_editor_item, self.extended_name + '_items?', remove = True ) super( SimpleEditor, self ).dispose() def update_editor ( self ): """ Updates the editor when the object facet changes externally to the editor. """ # Disconnect the editor from any control about to be destroyed: self._dispose_items() list_pane = self._list_pane layout = list_pane.layout() # Create all of the list item facet editors: facet_handler = self._facet_handler resizable = ((facet_handler.minlen != facet_handler.maxlen) and self.mutable) item_facet = facet_handler.item_facet values = self.value index = 0 is_fake = (resizable and (len( values ) == 0)) if is_fake: values = [ item_facet.default_value()[1] ] editor = self._editor # FIXME: Add support for more than one column. for value in values: if resizable: control = IconButton( '@facets:list_editor', self.popup_menu ) layout.addWidget( control, index, 0 ) try: proxy = ListItemProxy( self.object, self.name, index, item_facet, value ) if resizable: control.proxy = proxy peditor = editor( self.ui, proxy, 'value', self.description ).set( object_name = '' ) peditor.prepare( list_pane ) pcontrol = peditor.control pcontrol.proxy = proxy except: if not is_fake: raise pcontrol = QPushButton( 'sample', list_pane ) if isinstance( pcontrol, QWidget ): layout.addWidget( pcontrol, index, 1 ) else: layout.addLayout( pcontrol, index, 1 ) index += 1 if is_fake: self._cur_control = control self.empty_list() control.setParent( None ) if self.single_row: rows = 1 else: rows = self.factory.rows #list_pane.SetSize( wx.Size( # width + ((facet_handler.maxlen > rows) * scrollbar_dx), # height * rows ) ) # QScrollArea can have problems if the widget being scrolled is set too # early (ie. before it contains something). if self.control.widget() is None: self.control.setWidget( list_pane ) def update_editor_item ( self, object, name, old, event ): """ Updates the editor when an item in the object facet changes externally to the editor. """ # If this is not a simple, single item update, rebuild entire editor: if (len( event.removed ) != 1) or (len( event.added ) != 1): self.update_editor() return # Otherwise, find the proxy for this index and update it with the # changed value: for control in self.control.widget().children(): if isinstance( control, QLayout ): continue proxy = control.proxy if proxy.index == event.index: proxy.value = event.added[0] break def empty_list ( self ): """ Creates an empty list entry (so the user can add a new item). """ control = IconButton( '@facets:list_editor', self.popup_menu ) control.is_empty = True proxy = ListItemProxy( self.object, self.name, -1, None, None ) pcontrol = QLabel( ' (Empty List)' ) pcontrol.proxy = control.proxy = proxy self.reload_sizer( [ ( control, pcontrol ) ] ) def reload_sizer ( self, controls, extra = 0 ): """ Reloads the layout from the specified list of ( button, proxy ) pairs. """ layout = self._list_pane.layout() child = layout.takeAt( 0 ) while child is not None: child = layout.takeAt( 0 ) del child index = 0 for control, pcontrol in controls: layout.addWidget( control ) layout.addWidget( pcontrol ) control.proxy.index = index index += 1 def get_info ( self ): """ Returns the associated object list and current item index. """ proxy = self._cur_control.proxy return ( proxy.list, proxy.index ) def popup_empty_menu ( self, control ): """ Displays the empty list editor popup menu. """ self._cur_control = control control.PopupMenuXY( MakeMenu( self.empty_list_menu, self, True, control ).menu, 0, 0 ) def popup_menu ( self ): """ Displays the list editor popup menu. """ self._cur_control = control = self.control.sender() proxy = control.proxy index = proxy.index menu = MakeMenu( self.list_menu, self, True, control ).menu len_list = len( proxy.list ) not_full = ( len_list < self._facet_handler.maxlen ) self._menu_before.enabled( not_full ) self._menu_after.enabled( not_full ) self._menu_delete.enabled( len_list > self._facet_handler.minlen ) self._menu_up.enabled( index > 0 ) self._menu_top.enabled( index > 0 ) self._menu_down.enabled( index < (len_list - 1) ) self._menu_bottom.enabled( index < (len_list - 1) ) menu.exec_( control.mapToGlobal( QPoint( 0, 0 ) ) ) def add_item ( self, offset ): """ Adds a new value at the specified list index. """ list, index = self.get_info() index += offset item_facet = self._facet_handler.item_facet dv = item_facet.default_value() if dv[0] == 7: func, args, kw = dv[1] if kw is None: kw = {} value = func( *args, **kw ) else: value = dv[1] self.value = list[ : index ] + [ value ] + list[ index: ] self.update_editor() def add_before ( self ): """ Inserts a new item before the current item. """ self.add_item( 0 ) def add_after ( self ): """ Inserts a new item after the current item. """ self.add_item( 1 ) def add_empty ( self ): """ Adds a new item when the list is empty. """ list, index = self.get_info() self.add_item( 0 ) def delete_item ( self ): """ Delete the current item. """ list, index = self.get_info() self.value = list[ : index ] + list[ index + 1: ] self.update_editor() def move_up ( self ): """ Move the current item up one in the list. """ list, index = self.get_info() self.value = (list[ :index - 1 ] + [ list[ index ], list[ index - 1 ] ] + list[ index + 1: ]) def move_down ( self ): """ Moves the current item down one in the list. """ list, index = self.get_info() self.value = ( list[ : index ] + [ list[ index + 1 ], list[ index ] ] + list[ index + 2: ] ) def move_top ( self ): """ Moves the current item to the top of the list. """ list, index = self.get_info() self.value = [ list[ index ] ] + list[ : index ] + list[ index + 1: ] def move_bottom ( self ): """ Moves the current item to the bottom of the list. """ list, index = self.get_info() self.value = list[ : index ] + list[ index + 1: ] + [ list[ index ] ] #-- Private Methods -------------------------------------------------------- def _dispose_items ( self ): """ Disposes of each current list item. """ list_pane = self._list_pane layout = list_pane.layout() for control in list_pane.children(): editor = getattr( control, '_editor', None ) if editor is not None: editor.dispose() editor.control = None elif control is not layout: control.setParent( None ) del control
centralWidgetLayout = QVBoxLayout() centralWidget.setLayout(centralWidgetLayout) mainWindow.setCentralWidget(centralWidget) buttonsWidget = QWidget() buttonsLayout = QHBoxLayout() buttonsWidget.setLayout(buttonsLayout) buttonsWidget.show() for char in 'abracadabra': buttonsLayout.addWidget(QPushButton("Button '{0}'".format(char))) scrolledButtonsWidget = QScrollArea() scrolledButtonsWidget.setWidgetResizable(True) """ This property holds whether the scroll area should resize the view widget. If this property is set to false (the default), the scroll area honors the size of its widget. Regardless of this property, you can programmatically resize the widget using widget()->resize(), and the scroll area will automatically adjust itself to the new size. If this property is set to true, the scroll area will automatically resize the widget in order to avoid scroll bars where they can be avoided, or to take advantage of extra space. """ scrolledButtonsWidget.show() scrolledButtonsWidget.setWidget(buttonsWidget) """ Sets the scroll area's widget.
class PointsWidget(QWidget): """ PointsWidget """ activeLandmarkChanged = Signal(int) landmarkDeleted = Signal(int) def __init__(self): super(PointsWidget, self).__init__() self.landmarkWidgets = [] self.activeIndex = 0 self.scrollArea = QScrollArea(self) self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setAutoFillBackground(False) self.scrollArea.setAttribute(Qt.WA_TranslucentBackground) self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollArea.setWidgetResizable(True) landmarkLocationsLayout = QGridLayout() landmarkLocationsLayout.setSpacing(0) landmarkLocationsLayout.setContentsMargins(0, 0, 0, 0) landmarkLocationsLayout.setAlignment(Qt.AlignTop) self.landmarkLocationsWidget = QWidget() Style.styleWidgetForTab(self.landmarkLocationsWidget) self.landmarkLocationsWidget.setLayout(landmarkLocationsLayout) self.scrollArea.setWidget(self.landmarkLocationsWidget) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.scrollArea) self.setLayout(layout) @Slot(list) def setPoints(self, points): self._clearLandmarkWidgets() layout = self.landmarkLocationsWidget.layout() for index in range(len(points)): landmarkWidget = LandmarkLocationWidget() landmarkWidget.setIndex(index) landmarkWidget.active = (index == self.activeIndex) landmarkWidget.activated.connect(self.activateLandmark) landmarkWidget.deleted.connect(self.deleteLandmark) landmarkWidget.setLandmarkSet(points[index]) layout.addWidget(landmarkWidget, index, 0) self.landmarkWidgets.append(landmarkWidget) def _clearLandmarkWidgets(self): layout = self.landmarkLocationsWidget.layout() for widget in self.landmarkWidgets: widget.activated.disconnect() layout.removeWidget(widget) widget.deleteLater() self.landmarkWidgets = [] @Slot(int, object) def activateLandmark(self, index, state): if not state: self.activeIndex = len(self.landmarkWidgets) else: self.activeIndex = index self.activeLandmarkChanged.emit(self.activeIndex) @Slot(int) def deleteLandmark(self, index): self.activateLandmark(index, False) self.landmarkDeleted.emit(index)
def createMainWidget(self): """ TOWRITE :return: TOWRITE :rtype: `QScrollArea`_ """ widget = QWidget(self) # Misc groupBoxMisc = QGroupBox(self.tr("General Information"), widget) labelStitchesTotal = QLabel(self.tr("Total Stitches:"), self) labelStitchesReal = QLabel(self.tr("Real Stitches:"), self) labelStitchesJump = QLabel(self.tr("Jump Stitches:"), self) labelStitchesTrim = QLabel(self.tr("Trim Stitches:"), self) labelColorTotal = QLabel(self.tr("Total Colors:"), self) labelColorChanges = QLabel(self.tr("Color Changes:"), self) labelRectLeft = QLabel(self.tr("Left:"), self) labelRectTop = QLabel(self.tr("Top:"), self) labelRectRight = QLabel(self.tr("Right:"), self) labelRectBottom = QLabel(self.tr("Bottom:"), self) labelRectWidth = QLabel(self.tr("Width:"), self) labelRectHeight = QLabel(self.tr("Height:"), self) fieldStitchesTotal = QLabel(u'%s' % (self.stitchesTotal), self) fieldStitchesReal = QLabel(u'%s' % (self.stitchesReal), self) fieldStitchesJump = QLabel(u'%s' % (self.stitchesJump), self) fieldStitchesTrim = QLabel(u'%s' % (self.stitchesTrim), self) fieldColorTotal = QLabel(u'%s' % (self.colorTotal), self) fieldColorChanges = QLabel(u'%s' % (self.colorChanges), self) fieldRectLeft = QLabel(u'%s' % (str(self.boundingRect.left()) + " mm"), self) fieldRectTop = QLabel(u'%s' % (str(self.boundingRect.top()) + " mm"), self) fieldRectRight = QLabel(u'%s' % (str(self.boundingRect.right()) + " mm"), self) fieldRectBottom = QLabel(u'%s' % (str(self.boundingRect.bottom()) + " mm"), self) fieldRectWidth = QLabel(u'%s' % (str(self.boundingRect.width()) + " mm"), self) fieldRectHeight = QLabel(u'%s' % (str(self.boundingRect.height()) + " mm"), self) gridLayoutMisc = QGridLayout(groupBoxMisc) gridLayoutMisc.addWidget(labelStitchesTotal, 0, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelStitchesReal, 1, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelStitchesJump, 2, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelStitchesTrim, 3, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelColorTotal, 4, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelColorChanges, 5, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectLeft, 6, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectTop, 7, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectRight, 8, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectBottom, 9, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectWidth, 10, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectHeight, 11, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesTotal, 0, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesReal, 1, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesJump, 2, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesTrim, 3, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldColorTotal, 4, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldColorChanges, 5, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectLeft, 6, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectTop, 7, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectRight, 8, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectBottom, 9, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectWidth, 10, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectHeight, 11, 1, Qt.AlignLeft) gridLayoutMisc.setColumnStretch(1,1) groupBoxMisc.setLayout(gridLayoutMisc) # TODO: Color Histogram # Stitch Distribution # groupBoxDist = QGroupBox(self.tr("Stitch Distribution"), widget) # TODO: Stitch Distribution Histogram # Widget Layout vboxLayoutMain = QVBoxLayout(widget) vboxLayoutMain.addWidget(groupBoxMisc) # vboxLayoutMain.addWidget(groupBoxDist) vboxLayoutMain.addStretch(1) widget.setLayout(vboxLayoutMain) scrollArea = QScrollArea(self) scrollArea.setWidgetResizable(True) scrollArea.setWidget(widget) return scrollArea
class PrettySL(QWidget): def __init__(self, mainframe, op): QWidget.__init__(self) self.mainframe = mainframe self.op = op self.graph = self.op.link self.table = self.op.link.items self.lastButtonPressed = None self.needsRefresh = False self.subtree = [] self.delete = None self.initData() self.initUI() def initData(self): self.lab = None self.actionIDs = self.graph.getIDs() self.actionObjs = [] for act in self.table: self.actionObjs.append(act[0]) def initUI(self): self.grid = QGridLayout() self.setLayout(self.grid) self.tree = TreeWidget(self, self.actionObjs, self.actionIDs, self.table) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.tree) if self.tree.rect().width() < 600: self.scrollArea.setFixedWidth(self.tree.rect().width() + 25) else: self.scrollArea.setFixedWidth(600) if self.tree.rect().height() < 600: self.scrollArea.setFixedHeight(self.tree.rect().height()) else: self.scrollArea.setFixedHeight(600) self.scrollArea.ensureWidgetVisible(self.tree, 500, 500) self.grid.addWidget(self.scrollArea, 0, 0, 10, 3) self.legend = Legend(self) self.grid.addWidget(self.legend, 0, 3, 1, 2) self.setWindowModality(Qt.ApplicationModal) self.show() def trackIndex(self, index): print "Called" self.needsRefresh = True self.lastButtonPressed = index self.subtree = self.graph.subTree(index) print self.subtree self.initInfoUI(index) def deleteSubtree(self): if not popup( "Are you certain you want to delete this item and it's subtree?\n(Everything in red and yellow will be deleted)", "Warning"): return self.graph.delItem(self.lastButtonPressed) self.lab.close() self.initData() self.lastButtonPressed = None self.delete.close() self.delete = None self.subtree = [] self.needsRefresh = True self.idLabel.close() self.edit.clicked.disconnect() self.edit.close() self.op.linkstored.save() self.tree.close() self.tree = TreeWidget(self, self.actionObjs, self.actionIDs, self.table) self.grid.addWidget(self.tree, 0, 0, 10, 3) def initInfoUI(self, index): if not self.lab: self.lab = QLabel(self, text="Selected element summary:") self.grid.addWidget(self.lab, 2, 3, 1, 2) idt = "" if isinstance(self.table[index][0], Speak): idt += self.table[index][0].speaker + " says:\n\n" idt += self.actionIDs[index] self.idLabel = QLabel(self, text=idt) self.idLabel.setFixedSize(300, 40) self.idLabel.setWordWrap(True) self.grid.addWidget(self.idLabel, 3, 3, 1, 2) self.edit = QPushButton(self, text="Edit") self.edit.clicked.connect(lambda: self.enter(index)) self.grid.addWidget(self.edit, 4, 3, 1, 2) self.lkst = QLabel(self, text="Selected element links to:") self.grid.addWidget(self.lkst, 5, 3, 1, 2) self.rels = QLabel(self) self.rels.setMaximumWidth(300) text = "" for relation in self.table[index][1:len(self.table[index])]: text += "(" + str(relation) + ") " + self.graph.getOneID( self.table[relation][0]) + "\n\n" self.rels.setText(text) self.grid.addWidget(self.rels, 6, 3, 1, 2) else: text = "" idt = "" if isinstance(self.table[index][0], Speak): idt += self.table[index][0].speaker + " says:\n\n" idt += self.actionIDs[index] self.idLabel.setText(idt) for relation in self.table[index][1:len(self.table[index])]: text += "(" + str(relation) + ") " + self.graph.getOneID( self.table[relation][0]) + "\n\n" self.rels.setText(text) self.edit.clicked.disconnect() self.edit.clicked.connect(lambda: self.enter(index)) if not self.delete: self.delete = QPushButton(self, text="Delete element and subtree") self.delete.clicked.connect(self.deleteSubtree) self.grid.addWidget(self.delete, 1, 3, 1, 2) def enter(self, index): load = self.graph.getItem(index) self.close() self.op.view.setText("Graphic View") self.op.view.clicked.disconnect() self.op.view.clicked.connect(lambda: self.op.viewF(True)) self.op.listview.changeFrame(load, index)
class CustomCircuitCreator(QWidget): def __init__(self): super(CustomCircuitCreator, self).__init__() self.PaintArea = PaintArea(self) self.PaintArea.clearImage() self.grid = QGridLayout(self) self.grid.addWidget(self.PaintArea, 1, 0, 1, 9) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.createToolsButtons() self.createButtons() self.setWindowTitle("Custom circuit creator") self.resize(self.PaintArea.size_w, self.PaintArea.size_h + 85) def closeEvent(self, event): if self.maybeSave(): event.accept() else: event.ignore() def createButtons(self): buttonsDialog = QDialogButtonBox(self) buttonsDialog.setStandardButtons( QDialogButtonBox.Save | QDialogButtonBox.Cancel | QDialogButtonBox.Reset) self.grid.addWidget(buttonsDialog, 3, 0, 3, 9) buttonsDialog.button(QDialogButtonBox.Save).clicked.connect( self.saveFile) buttonsDialog.button(QDialogButtonBox.Reset).clicked.connect( self.PaintArea.clearImage) buttonsDialog.button(QDialogButtonBox.Cancel).clicked.connect( self.close) def createToolsButtons(self): buttonsFrame = QFrame() buttonsLayout = QHBoxLayout(buttonsFrame) buttonsLayout.setSizeConstraint(QLayout.SetDefaultConstraint) iconPath = filePath('icons/') self.penButton = QToolButton( self, icon=QIcon(iconPath + 'pen_w.png')) self.penButton.setToolTip('freehand drawing') self.penButton.clicked.connect(lambda: self.PaintArea.setTool('pen')) buttonsLayout.addWidget(self.penButton) self.lineButton = QToolButton( self, icon=QIcon(iconPath + 'line_w.png')) self.lineButton.setToolTip('draw lines') self.lineButton.clicked.connect(lambda: self.PaintArea.setTool('line')) buttonsLayout.addWidget(self.lineButton) self.rect = QToolButton( self, icon=QIcon(iconPath + 'rect_w.png')) self.rect.setToolTip('create rectangle') self.rect.clicked.connect(lambda: self.PaintArea.setTool('rect')) buttonsLayout.addWidget(self.rect) self.roundRect = QToolButton( self, icon=QIcon(iconPath + 'roundrect_w.png')) self.roundRect.setToolTip('create a round-corner rectanlge') self.roundRect.clicked.connect( lambda: self.PaintArea.setTool('roundRect')) buttonsLayout.addWidget(self.roundRect) self.circle = QToolButton( self, icon=QIcon(iconPath + 'ellipse_w.png')) self.circle.setToolTip('create circle') self.circle.clicked.connect(lambda: self.PaintArea.setTool('circle')) buttonsLayout.addWidget(self.circle) self.eraser = QToolButton( self, icon=QIcon(iconPath + 'eraser_w.png')) self.eraser.setToolTip('erase parts of the drawing') self.eraser.clicked.connect(lambda: self.PaintArea.setTool('eraser')) buttonsLayout.addWidget(self.eraser) self.mirror_w = QToolButton( self, icon=QIcon(iconPath + 'mirror-w_w.png')) self.mirror_w.setToolTip('vertical symmetric inversion') self.mirror_w.clicked.connect(self.PaintArea.mirror_w) buttonsLayout.addWidget(self.mirror_w) self.mirror_h = QToolButton( self, icon=QIcon(iconPath + 'mirror-h_w.png')) self.mirror_h.setToolTip('horizontal symmetric inversion') self.mirror_h.clicked.connect(self.PaintArea.mirror_h) buttonsLayout.addWidget(self.mirror_h) self.rotate = QToolButton( self, icon=QIcon(iconPath + 'rotate_w.png')) self.rotate.setToolTip('rotate') self.rotate.clicked.connect(self.PaintArea.rotate) buttonsLayout.addWidget(self.rotate) self.grid.addWidget(buttonsFrame, 0, 0, QtCore.Qt.AlignLeft) def maybeSave(self): if self.PaintArea.isModified(): ret = QMessageBox.warning( self, "Save your work", "The drawing has been modified.\n" "Do you want to save your changes ?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: return self.saveFile('png') elif ret == QMessageBox.Cancel: return False return True def saveFile(self, fileFormat='png'): initialPath = QtCore.QDir.currentPath() + '/customCirc.' + fileFormat fileName = QFileDialog.getSaveFileName( self, "Save As", initialPath, "%s Files (*.%s);;All Files (*)" % (fileFormat.upper(), fileFormat)) if fileName: if self.PaintArea.saveImage('customCirc.' + fileFormat): self.close()
def __init__(self, user, parent): super(UserDetailsWindow, self).__init__(parent) self.user = user self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(11, 11, 11, 11) self.centralWidget.setLayout(layout) self.container = QWidget() self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.container) self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) layout.addWidget(self.scrollArea) self.scrollArea.setWidgetResizable(True) gridLayout = QGridLayout() self.container.setLayout(gridLayout) firstName = user['user']['firstName'] name = firstName if 'lastName' in user['user']: name += " " + user['user']['lastName'] self.setWindowTitle(name) photo_label = QLabel() photo = QImage(foursquare.image(self.user['user']['photo'])) photo_label.setPixmap(QPixmap(photo)) i = 0 gridLayout.addWidget(UserProfile(user), i, 0, 1, 2) ### checkin button if user['user']['relationship'] != "self": i += 1 self.shoutText = QLineEdit(self) self.shoutText.setPlaceholderText("Shout something") gridLayout.addWidget(self.shoutText, i, 0) checkinButton = QPushButton("Check-in with " + firstName) self.connect(checkinButton, SIGNAL("clicked()"), self.checkin) gridLayout.addWidget(checkinButton, i, 1) # TODO! #if user['user']['relationship'] == "friend": # i += 1 # gridLayout.addWidget(QLabel("TODO: Unfriend"), i, 0, 1, 2) elif user['user']['relationship'] == "self": i += 1 gridLayout.addWidget(QLabel("It's you!"), i, 0, 1, 2) if user['user']['id'] == "17270875": i += 1 gridLayout.addWidget(QLabel("<b>This is the UberSquare developer!</b>"), i, 0, 1, 2) i += 1 checkins = user['user']['checkins']['count'] gridLayout.addWidget(QLabel(str(checkins) + " checkins"), i, 0) i += 1 badges = user['user']['badges']['count'] gridLayout.addWidget(QLabel(str(badges) + " badges"), i, 0) i += 1 mayorships = user['user']['mayorships']['count'] if mayorships > 0: mayorshipsButton = QPushButton(str(mayorships) + " mayorships") mayorshipsButton.setIcon(QIcon(foursquare.image("https://foursquare.com/img/points/mayor.png"))) self.connect(mayorshipsButton, SIGNAL("clicked()"), self.mayorships_pushed) gridLayout.addWidget(mayorshipsButton, i, 0, 1, 2) else: gridLayout.addWidget(QLabel("No mayorships"), i, 0) i += 1 # TODO! #gridLayout.addWidget(QPushButton("TODO: See places " + firstName + " has been to."), i, 0, 1, 2) #i += 1 update_user_button = QPushButton("Refresh user details") update_user_button.setIcon(QIcon.fromTheme("general_refresh")) self.connect(update_user_button, SIGNAL("clicked()"), self.__update) gridLayout.addWidget(update_user_button, i, 0, 1, 2) showUser = Signal() self.connect(self, SIGNAL("showUser()"), self.__showUser)
class RenderParameterWidget(QWidget): """ RenderParameterWidget is a widget that is shown in the render property widget. It holds a combo box with which different visualizations can be chosen. Beneath the combo box it displays a widget in a scroll view that contains widgets with which parameters of the visualization can be adjusted. """ def __init__(self, renderController, parent=None): super(RenderParameterWidget, self).__init__(parent=parent) self.renderController = renderController self.renderController.visualizationChanged.connect(self.visualizationLoaded) self.paramWidget = None self.visTypeComboBox = QComboBox() for visualizationType in self.renderController.visualizationTypes: self.visTypeComboBox.addItem(visualizationType) layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setSpacing(10) layout.setContentsMargins(10, 0, 10, 0) if len(self.renderController.visualizationTypes) > 1: layout.addWidget(QLabel("Visualization type:"), 0, 0) layout.addWidget(self.visTypeComboBox, 0, 1) self.setLayout(layout) self.scrollArea = QScrollArea() self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setAutoFillBackground(False) self.scrollArea.setAttribute(Qt.WA_TranslucentBackground) self.scrollArea.setWidgetResizable(True) self.visTypeComboBox.currentIndexChanged.connect(self.visTypeComboBoxChanged) def UpdateWidgetFromRenderWidget(self): """ Update the parameter widget with a widget from the render widget. """ # Add the scroll area for the parameter widget if it is not there yet layout = self.layout() if layout.indexOf(self.scrollArea) == -1: layout.addWidget(self.scrollArea, 1, 0, 1, 2) self.setLayout(layout) # Clear the previous parameter widget if self.paramWidget is not None: self.paramWidget.setParent(None) if self.renderController.visualization is not None: self.renderController.visualization.disconnect(SIGNAL("updatedTransferFunction"), self.transferFunctionChanged) # Get a new parameter widget from the render widget self.paramWidget = self.renderController.getParameterWidget() Style.styleWidgetForTab(self.paramWidget) self.scrollArea.setWidget(self.paramWidget) if self.renderController.visualization is not None: self.renderController.visualization.updatedTransferFunction.connect(self.transferFunctionChanged) self.visTypeComboBox.setCurrentIndex(self.visTypeComboBox.findText(self.renderController.visualizationType)) @Slot(int) def visTypeComboBoxChanged(self, index): """ Slot that changes the render type. Also updates parameters and makes sure that the renderWidget renders with the new visualizationType. :type index: any """ self.renderController.setVisualizationType(self.visTypeComboBox.currentText()) self.UpdateWidgetFromRenderWidget() self.renderController.updateVisualization() def visualizationLoaded(self, visualization): self.UpdateWidgetFromRenderWidget() @Slot() def transferFunctionChanged(self): """ Slot that can be used when a transfer function has changed so that the render will be updated afterwards. Should be called on valueChanged by the widgets from the parameter widget. """ self.renderController.updateVisualization()
def createMainWidget(self): """ TOWRITE :return: TOWRITE :rtype: QScrollArea """ widget = QWidget(self) # Misc groupBoxMisc = QGroupBox(self.tr("General Information"), widget) labelStitchesTotal = QLabel(self.tr("Total Stitches:"), self) labelStitchesReal = QLabel(self.tr("Real Stitches:"), self) labelStitchesJump = QLabel(self.tr("Jump Stitches:"), self) labelStitchesTrim = QLabel(self.tr("Trim Stitches:"), self) labelColorTotal = QLabel(self.tr("Total Colors:"), self) labelColorChanges = QLabel(self.tr("Color Changes:"), self) labelRectLeft = QLabel(self.tr("Left:"), self) labelRectTop = QLabel(self.tr("Top:"), self) labelRectRight = QLabel(self.tr("Right:"), self) labelRectBottom = QLabel(self.tr("Bottom:"), self) labelRectWidth = QLabel(self.tr("Width:"), self) labelRectHeight = QLabel(self.tr("Height:"), self) fieldStitchesTotal = QLabel(u'%s' % (self.stitchesTotal), self) fieldStitchesReal = QLabel(u'%s' % (self.stitchesReal), self) fieldStitchesJump = QLabel(u'%s' % (self.stitchesJump), self) fieldStitchesTrim = QLabel(u'%s' % (self.stitchesTrim), self) fieldColorTotal = QLabel(u'%s' % (self.colorTotal), self) fieldColorChanges = QLabel(u'%s' % (self.colorChanges), self) fieldRectLeft = QLabel(u'%s' % (str(self.boundingRect.left()) + " mm"), self) fieldRectTop = QLabel(u'%s' % (str(self.boundingRect.top()) + " mm"), self) fieldRectRight = QLabel( u'%s' % (str(self.boundingRect.right()) + " mm"), self) fieldRectBottom = QLabel( u'%s' % (str(self.boundingRect.bottom()) + " mm"), self) fieldRectWidth = QLabel( u'%s' % (str(self.boundingRect.width()) + " mm"), self) fieldRectHeight = QLabel( u'%s' % (str(self.boundingRect.height()) + " mm"), self) gridLayoutMisc = QGridLayout(groupBoxMisc) gridLayoutMisc.addWidget(labelStitchesTotal, 0, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelStitchesReal, 1, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelStitchesJump, 2, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelStitchesTrim, 3, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelColorTotal, 4, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelColorChanges, 5, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectLeft, 6, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectTop, 7, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectRight, 8, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectBottom, 9, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectWidth, 10, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(labelRectHeight, 11, 0, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesTotal, 0, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesReal, 1, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesJump, 2, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldStitchesTrim, 3, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldColorTotal, 4, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldColorChanges, 5, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectLeft, 6, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectTop, 7, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectRight, 8, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectBottom, 9, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectWidth, 10, 1, Qt.AlignLeft) gridLayoutMisc.addWidget(fieldRectHeight, 11, 1, Qt.AlignLeft) gridLayoutMisc.setColumnStretch(1, 1) groupBoxMisc.setLayout(gridLayoutMisc) # TODO: Color Histogram # Stitch Distribution # groupBoxDist = QGroupBox(self.tr("Stitch Distribution"), widget) # TODO: Stitch Distribution Histogram # Widget Layout vboxLayoutMain = QVBoxLayout(widget) vboxLayoutMain.addWidget(groupBoxMisc) # vboxLayoutMain.addWidget(groupBoxDist) vboxLayoutMain.addStretch(1) widget.setLayout(vboxLayoutMain) scrollArea = QScrollArea(self) scrollArea.setWidgetResizable(True) scrollArea.setWidget(widget) return scrollArea
class RenderInfoWidget(QWidget): """ RenderInfoWidget shows information about the loaded dataset. Things like filenames, range of data values, size of data, etc. """ def __init__(self): super(RenderInfoWidget, self).__init__() self.scrollArea = QScrollArea() self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setAutoFillBackground(False) self.scrollArea.setAttribute(Qt.WA_TranslucentBackground) self.scrollArea.setWidgetResizable(True) Style.styleWidgetForTab(self) Style.styleWidgetForTab(self.scrollArea) @Slot(basestring) def setFile(self, fileName): """ Slot that reads properties of the dataset and displays them in a few widgets. """ if fileName is None: return self.fileName = fileName # Read info from dataset # TODO: read out the real world dimensions in inch or cm # TODO: scalar type (int, float, short, etc.) imageReader = DataReader() imageData = imageReader.GetImageData(fileName) directory, name = os.path.split(fileName) dimensions = imageData.GetDimensions() minimum, maximum = imageData.GetScalarRange() scalarType = imageData.GetScalarTypeAsString() bins = DataAnalyzer.histogramForData(imageData, 256) self.histogram = Histogram() self.histogram.bins = bins self.histogram.enabled = True self.histogramWidget = HistogramWidget() self.histogramWidget.setMinimumHeight(100) self.histogramWidget.setHistogram(self.histogram) self.histogramWidget.setAxeMode(bottom=HistogramWidget.AxeClear, left=HistogramWidget.AxeLog) Style.styleWidgetForTab(self.histogramWidget) nameText = name dimsText = "(" + str(dimensions[0]) + ", " + str(dimensions[1]) + ", " + str(dimensions[2]) + ")" voxsText = str(dimensions[0] * dimensions[1] * dimensions[2]) rangText = "[" + str(minimum) + " : " + str(maximum) + "]" typeText = scalarType layout = self.layout() if not layout: # Create a new layout layout = QGridLayout() layout.setAlignment(Qt.AlignTop) # Create string representations nameLabels = [] nameLabels.append(QLabel("File name:")) nameLabels.append(QLabel("Dimensions:")) nameLabels.append(QLabel("Voxels:")) nameLabels.append(QLabel("Range:")) nameLabels.append(QLabel("Data type:")) for label in nameLabels: label.setAlignment(Qt.AlignRight | Qt.AlignVCenter) # Create 'dynamic' labels self.labelTitle = QLabel(nameText) self.labelDimensions = QLabel(dimsText) self.labelVoxels = QLabel(voxsText) self.labelRange = QLabel(rangText) self.labelType = QLabel(typeText) index = 0 for label in nameLabels: layout.addWidget(label, index, 0) index += 1 layout.addWidget(self.labelTitle, 0, 1) layout.addWidget(self.labelDimensions, 1, 1) layout.addWidget(self.labelVoxels, 2, 1) layout.addWidget(self.labelRange, 3, 1) layout.addWidget(self.labelType, 4, 1) layout.addWidget(self.histogramWidget, 5, 0, 1, 2) widget = QWidget() widget.setLayout(layout) Style.styleWidgetForTab(widget) self.scrollArea.setWidget(widget) scrollLayout = QGridLayout() scrollLayout.setSpacing(0) scrollLayout.setContentsMargins(0, 0, 0, 0) scrollLayout.addWidget(self.scrollArea) self.setLayout(scrollLayout) else: # Just update the text for the 'dynamic' labels self.labelTitle.setText(nameText) self.labelDimensions.setText(dimsText) self.labelVoxels.setText(voxsText) self.labelRange.setText(rangText) self.labelType.setText(typeText)
def __init__(self, parent=None): QScrollArea.__init__(self, parent) self.setStyleSheet("background-color: transparent")
class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setGeometry(0, 0, 1500, 1000) self.move( QApplication.desktop().screen().rect().center() - self.rect().center()) self.show() # Main layout self.layout = QHBoxLayout() self.setLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) self.atoms = odict() titles = odict([ ["preset", "Presets"], ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Constaint on hubble parameter"], ["baryons", "Baryon sector"], ["dark_matter", "Dark matter"], ["dark_energy", "Lambda / Dark energy"], ["neutrinos", "Neutrinos and other extra matter"], ["bbn", "BBN"], ["reionization", "Reionization history"], ["cmb_lensing", "CMB lensing"], ["cmb", "CMB experiments"], ["sampler", "Samplers"]]) for a in titles: self.atoms[a] = { "group": QGroupBox(titles[a]), "combo": QComboBox()} self.layout_options.addWidget(self.atoms[a]["group"]) self.atoms[a]["layout"] = QVBoxLayout(self.atoms[a]["group"]) self.atoms[a]["layout"].addWidget(self.atoms[a]["combo"]) self.atoms[a]["combo"].addItems( [text(k,v) for k,v in getattr(input_database, a).items()]) # Connect to refreshers -- needs to be after adding all elements for a in self.atoms: if a == "preset": self.atoms["preset"]["combo"].currentIndexChanged.connect( self.refresh_preset) continue self.atoms[a]["combo"].currentIndexChanged.connect(self.refresh) # Add Planck-naming checkbox and connect to refresher too self.planck_names = QCheckBox("Keep common names") self.atoms["theory"]["layout"].addWidget(self.planck_names) self.planck_names.stateChanged.connect(self.refresh) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave) # Select first preset, by default # print(self.atoms["preset"]["combo"].itemText(0)) @Slot() def refresh(self): info = create_input(planck_names=self.planck_names.isChecked(), **{ k:str(self.atoms[k]["combo"].currentText().split(_separator)[0]) for k in self.atoms if k is not "preset"}) self.refresh_display(info) @Slot() def refresh_preset(self): preset = self.atoms["preset"]["combo"].currentText().split(_separator)[0] info = create_input(preset=preset) self.refresh_display(info) # Update combo boxes to reflect the preset values, without triggering update for k,v in input_database.preset[preset].items(): if k in [input_database._desc, "derived"]: continue self.atoms[k]["combo"].blockSignals(True) self.atoms[k]["combo"].setCurrentIndex( self.atoms[k]["combo"].findText( text(v,getattr(input_database, k).get(v)))) self.atoms[k]["combo"].blockSignals(False) def refresh_display(self, info): self.display["python"].setText( "from collections import OrderedDict\n\ninfo = " + pformat(info)) self.display["yaml"].setText(yaml_dump(info)) @Slot() def save_file(self): ftype = next(k for k,w in self.display.items() if w is self.display_tabs.currentWidget()) ffilter = {"yaml": "Yaml files (*.yaml *.yml)", "python": "(*.py)"}[ftype] fsuffix = {"yaml": ".yaml", "python": ".py"}[ftype] fname, path = self.save_dialog.getSaveFileName( self.save_dialog, "Save input file", fsuffix, ffilter, os.getcwd()) if not fname.endswith(fsuffix): fname += fsuffix with open(fname, "w+") as f: f.write(self.display_tabs.currentWidget().toPlainText()) @Slot() def copy_clipb(self): self.clipboard.setText(self.display_tabs.currentWidget().toPlainText())