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_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 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 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_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 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 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, 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_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 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(Widget_TypeAttributeList, self).__init__(*args, **kwargs) self.installEventFilter(self) mainLayout = QVBoxLayout(self) mainLayout.setContentsMargins(0, 0, 0, 5) groupBox = QGroupBox("Search Attribute Types") groupBoxLayout = QVBoxLayout() groupBox.setStyleSheet("font-size:12px") groupBox.setLayout(groupBoxLayout) groupBoxLayout.setContentsMargins(0, 0, 0, 0) scrollArea = QScrollArea() scrollArea.setStyleSheet("font-size:11px") scrollAreaWidget = QWidget() scrollAreaLayout = QVBoxLayout(scrollAreaWidget) scrollArea.setWidgetResizable(True) scrollArea.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored) scrollArea.setWidget(scrollAreaWidget) scrollAreaLayout.setContentsMargins(5, 0, 5, 0) scrollArea.resize(scrollArea.sizeHint()) groupBoxLayout.addWidget(scrollArea) self.get_csv_form_google_spreadsheets(Widget_TypeAttributeList.url, Widget_TypeAttributeList.csv) dict_list = self.get_dictList_from_csvPath( Widget_TypeAttributeList.csv) self.w_typeAttrs = [] for dict_data in dict_list: w_typeAttr = Widget_TypeAttribute(attr_name=dict_data['attr_name'], type_node=dict_data['type_node']) scrollAreaLayout.addWidget(w_typeAttr) self.w_typeAttrs.append(w_typeAttr) empty = QLabel() empty.setMinimumHeight(0) scrollAreaLayout.addWidget(empty) mainLayout.addWidget(groupBox) self.resize(0, 100)
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 __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)
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()))
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)
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 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
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)
class ImageViewer(QWidget): """A custom widget to display an image in Gui.""" # Inspired by : # https://doc.qt.io/qt-6/qtwidgets-widgets-imageviewer-example.html # https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/widgets/imageviewer 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 add_actions_to_menu(self, menu): """Add widget actions to a given menu. Args: menu -- the menu to add the actions (QMenu) """ zoom_in_act = menu.addAction("Zoom In (25%)") zoom_in_act.triggered.connect(self.zoom_in) zoom_out_act = menu.addAction("Zoom Out (25%)") zoom_out_act.triggered.connect(self.zoom_out) zoom_normal_act = menu.addAction("Normal Size") zoom_normal_act.triggered.connect(self.normal_size) menu.addSeparator() copy_filename_act = menu.addAction("Copy Image to Clipboard") copy_filename_act.triggered.connect(self.copy_image) copy_filename_act = menu.addAction("Copy Filename to Clipboard") copy_filename_act.triggered.connect(self.copy_filename) def load_image(self, img_path): """Load an image in widget from a file. Args: img_path -- Path of image file to load (str) """ img_path = str(img_path) pixmap = QPixmap(img_path) self.imglabel.setPixmap(pixmap) self.imglabel.resize(pixmap.size()) self.namelabel.setText(f"File: {img_path}") self._img_path = img_path self._initial_size = pixmap.size() def resize_image(self, new_size=None): """Resize embedded image to target size. Args: new_size -- target size to resize image to (QSize) """ if not new_size: new_size = self._initial_size self.scale_factor = 1.0 new_size = QSize(new_size) self.imglabel.setMinimumSize(new_size) self.imglabel.setMaximumSize(new_size) def scale_image(self, factor): """Rescale embedded image applying a factor. Factor is applied relatively to current scale. Args: factor -- Factor to apply (float) """ self.scale_factor *= float(factor) new_size = self.scale_factor * self._initial_size self.resize_image(new_size) @Slot() def zoom_in(self): """Zoom embedded image in (slot).""" self.scale_image(1.25) @Slot() def zoom_out(self): """Zoom embedded image out (slot).""" self.scale_image(0.8) @Slot() def normal_size(self): """Set embedded image scale to 1:1 (slot).""" self.resize_image() @Slot() def copy_filename(self): """Copy file name to clipboard (slot).""" QGuiApplication.clipboard().setText(self._img_path) @Slot() def copy_image(self): """Copy embedded image to clipboard (slot).""" QGuiApplication.clipboard().setImage(self.imglabel.pixmap().toImage()) @Slot(QPoint) def show_context_menu(self, pos): """Show context menu.""" self.menu.exec_(self.mapToGlobal(pos))
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 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())
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. The widget becomes a child of the scroll area, and will be destroyed when the scroll area is deleted or when a new widget is set.
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
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)
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()
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().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) def create_input(self): return create_input( get_comments=True, # planck_names=self.planck_names.isChecked(), **{field: list(getattr(input_database, field).keys())[combo.currentIndex()] for field, combo in self.combos.items() if field is not "preset"}) @Slot() def refresh_keep_preset(self): self.refresh_display(self.create_input()) @Slot() def refresh(self): self.combos["preset"].blockSignals(True) self.combos["preset"].setCurrentIndex(0) self.combos["preset"].blockSignals(False) self.refresh_display(self.create_input()) @Slot() def refresh_preset(self): preset = list(getattr(input_database, "preset").keys())[ self.combos["preset"].currentIndex()] info = create_input( get_comments=True, # planck_names=self.planck_names.isChecked(), 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]: continue self.combos[k].blockSignals(True) self.combos[k].setCurrentIndex( self.combos[k].findText( text(v, getattr(input_database, k).get(v)))) self.combos[k].blockSignals(False) def refresh_display(self, info): try: comments = info.pop(input_database._comment, None) comments_text = "\n# " + "\n# ".join(comments) except (TypeError, # No comments AttributeError): # Failed to generate info (returned str instead) comments_text = "" self.display["python"].setText( "from collections import OrderedDict\n\ninfo = " + pformat(info) + comments_text) self.display["yaml"].setText(yaml_dump(info) + comments_text) self.display["citations"].setText(prettyprint_citation(citation(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)", "citations": "(*.txt)"}[ftype] fsuffix = {"yaml": ".yaml", "python": ".py", "citations": ".txt"}[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())