Beispiel #1
0
 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)
Beispiel #2
0
    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')
Beispiel #3
0
Datei: gui.py Projekt: caomw/ecto
 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)
Beispiel #4
0
    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_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)
Beispiel #6
0
    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):

        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)
Beispiel #8
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)
Beispiel #9
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)
Beispiel #10
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
Beispiel #11
0
 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)
Beispiel #12
0
    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)
Beispiel #13
0
 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)  
Beispiel #14
0
 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)
Beispiel #15
0
        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)
Beispiel #16
0
    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)
Beispiel #17
0
 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()))
Beispiel #18
0
    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)
Beispiel #19
0
 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)
Beispiel #20
0
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)
Beispiel #21
0
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
Beispiel #22
0
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))
Beispiel #23
0
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()
Beispiel #24
0
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())
Beispiel #25
0
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)
    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.

The widget's autoFillBackground property will be set to true.

If the scroll area is visible when the widget is added, you must show() it explicitly.

Note that You must add the layout of widget before you call this function; if you add it later, the widget will not be visible - regardless of when you show() the scroll area. In this case, you can also not show() the widget later.
"""

scrolledButtonsWidget.adjustSize()

centralWidgetLayout.addWidget(scrolledButtonsWidget)
Beispiel #27
0
    def setup(self):
        """initializes the uio of the erp client"""
        self.progress.setFixedWidth(1000)
        self.progress.setCancelButton(None)
        # self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setValue(1)
        self.mainwindow.setObjectName("MainWindow")
        self.mainwindow.resize(832, 668)
        self.mainwindow.setStyleSheet(
            "QToolBar{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "QToolBar > QWidget{\n"
            "color:white;\n"
            "}\n"
            "QToolBar > QWidget:hover {\n"
            "background:transparent;\n"
            " }\n"
            "QToolBar > QWidget:checked {\n"
            "background:transparent;\n"
            " }\n"
            "#MainWindow{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "")
        self.centralWidget = QWidget(self.mainwindow)
        self.centralWidget.setObjectName("centralWidget")
        self.gridLayout_2 = QGridLayout(self.centralWidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.stackedWidget = QStackedWidget(self.centralWidget)
        self.stackedWidget.setStyleSheet("")
        self.stackedWidget.setObjectName("stackedWidget")
        self.shortcut = NewShortcut()
        scroll = QScrollArea()
        scroll.setWidget(self.shortcut.shortcut_setting)
        self.stackedWidget.addWidget(self.shortcut.shortcut_setting)
        self.home_page = QWidget()
        self.home_page.setObjectName("home_page")
        self.gridLayout = QGridLayout(self.home_page)
        self.gridLayout.setObjectName("gridLayout")
        self.billing_frame_2 = QFrame(self.home_page)
        self.billing_frame_2.setStyleSheet(
            "background-image:url(:/images/billing_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#6CBED2;")
        self.billing_frame_2.setFrameShape(QFrame.StyledPanel)
        self.billing_frame_2.setFrameShadow(QFrame.Raised)
        self.billing_frame_2.setObjectName("billing_frame_2")
        self.verticalLayout_4 = QVBoxLayout(self.billing_frame_2)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        spacerItem = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_4.addItem(spacerItem)
        self.label_10 = QLabel(self.billing_frame_2)
        self.label_10.setStyleSheet("background:transparent;")
        self.label_10.setObjectName("label_10")
        self.verticalLayout_4.addWidget(self.label_10)
        self.gridLayout.addWidget(self.billing_frame_2, 0, 1, 1, 1)
        self.employee_frame_3 = QFrame(self.home_page)
        self.employee_frame_3.setStyleSheet(
            "background-image:url(:/images/employee_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#0099CC;")
        self.employee_frame_3.setFrameShape(QFrame.StyledPanel)
        self.employee_frame_3.setFrameShadow(QFrame.Raised)
        self.employee_frame_3.setObjectName("employee_frame_3")
        self.verticalLayout_5 = QVBoxLayout(self.employee_frame_3)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        spacerItem1 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_5.addItem(spacerItem1)
        self.label_11 = QLabel(self.employee_frame_3)
        self.label_11.setStyleSheet("background:transparent;")
        self.label_11.setObjectName("label_11")
        self.verticalLayout_5.addWidget(self.label_11)
        self.gridLayout.addWidget(self.employee_frame_3, 0, 2, 1, 1)
        self.menu_frame_4 = QFrame(self.home_page)
        self.menu_frame_4.setStyleSheet(
            "background-image:url(:/images/menu_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#297ACC;")
        self.menu_frame_4.setFrameShape(QFrame.StyledPanel)
        self.menu_frame_4.setFrameShadow(QFrame.Raised)
        self.menu_frame_4.setObjectName("menu_frame_4")
        self.verticalLayout_3 = QVBoxLayout(self.menu_frame_4)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        spacerItem2 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_3.addItem(spacerItem2)
        self.label_12 = QLabel(self.menu_frame_4)
        self.label_12.setStyleSheet("background:transparent;")
        self.label_12.setObjectName("label_12")
        self.verticalLayout_3.addWidget(self.label_12)
        self.gridLayout.addWidget(self.menu_frame_4, 1, 0, 1, 1)
        self.report_frame_5 = QFrame(self.home_page)
        self.report_frame_5.setStyleSheet(
            "background-image:url(:/images/report_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#006BB2;")
        self.report_frame_5.setFrameShape(QFrame.StyledPanel)
        self.report_frame_5.setFrameShadow(QFrame.Raised)
        self.report_frame_5.setObjectName("report_frame_5")
        self.verticalLayout_6 = QVBoxLayout(self.report_frame_5)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        spacerItem3 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_6.addItem(spacerItem3)
        self.label_13 = QLabel(self.report_frame_5)
        self.label_13.setStyleSheet("background:transparent;")
        self.label_13.setObjectName("label_13")
        self.verticalLayout_6.addWidget(self.label_13)
        self.gridLayout.addWidget(self.report_frame_5, 1, 1, 1, 1)
        self.waste_frame_6 = QFrame(self.home_page)
        self.waste_frame_6.setStyleSheet(
            "background-image:url(:/images/waste_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#003D7A;")
        self.waste_frame_6.setFrameShape(QFrame.StyledPanel)
        self.waste_frame_6.setFrameShadow(QFrame.Raised)
        self.waste_frame_6.setObjectName("waste_frame_6")
        self.verticalLayout_7 = QVBoxLayout(self.waste_frame_6)
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        spacerItem4 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_7.addItem(spacerItem4)
        self.label_14 = QLabel(self.waste_frame_6)
        self.label_14.setStyleSheet("background:transparent;")
        self.label_14.setObjectName("label_14")
        self.verticalLayout_7.addWidget(self.label_14)
        self.gridLayout.addWidget(self.waste_frame_6, 1, 2, 1, 1)
        self.inventory_frame_1 = QFrame(self.home_page)
        self.inventory_frame_1.setStyleSheet(
            "background-image:url(:/images/inventory_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#ADEBFF;")
        self.inventory_frame_1.setFrameShape(QFrame.StyledPanel)
        self.inventory_frame_1.setFrameShadow(QFrame.Raised)
        self.inventory_frame_1.setObjectName("inventory_frame_1")
        self.verticalLayout_2 = QVBoxLayout(self.inventory_frame_1)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        spacerItem5 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem5)
        self.label_9 = QLabel(self.inventory_frame_1)
        self.label_9.setStyleSheet("background:transparent;")
        self.label_9.setObjectName("label_9")
        self.verticalLayout_2.addWidget(self.label_9)
        self.gridLayout.addWidget(self.inventory_frame_1, 0, 0, 1, 1)
        self.stackedWidget.addWidget(self.home_page)
        self.detail_page = QWidget()
        self.detail_page.setObjectName("detail_page")
        self.horizontalLayout_2 = QHBoxLayout(self.detail_page)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.main_tabWidget = QTabWidget(self.detail_page)
        self.main_tabWidget.setAutoFillBackground(False)
        self.main_tabWidget.setStyleSheet("")
        self.main_tabWidget.setTabPosition(QTabWidget.West)
        self.main_tabWidget.setIconSize(QSize(60, 60))
        self.main_tabWidget.setElideMode(Qt.ElideNone)
        self.main_tabWidget.setObjectName("main_tabWidget")
        ##initializes the tabs
        self.add_tabs()
        self.main_tabWidget.setFocusPolicy(Qt.StrongFocus)
        self.main_tabWidget.focusInEvent = self.change_focus
        self.main_tabWidget.currentChanged.connect(self.change_focus)
        self.stackedWidget.currentChanged.connect(self.change_focus)
        ######
        self.horizontalLayout_2.addWidget(self.main_tabWidget)
        self.stackedWidget.addWidget(self.detail_page)
        if ('Admin', True) in self.access:
            self.stackedWidget.addWidget(Admin(self.mainwindow))
        notification = NotificationTab()
        tab = notification.notificationTab_tab_4
        tab.custom_class_object = notification  # class_object is used to access the api through the
        self.stackedWidget.addWidget(tab)
        self.gridLayout_2.addWidget(self.stackedWidget, 0, 0, 1, 1)
        self.mainwindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(self.mainwindow)
        self.menuBar.setGeometry(QRect(0, 0, 832, 29))
        self.menuBar.setObjectName("menuBar")
        self.mainwindow.setMenuBar(self.menuBar)
        self.mainToolBar = QToolBar(self.mainwindow)
        self.mainToolBar.setLayoutDirection(Qt.RightToLeft)
        self.mainToolBar.setStyleSheet("")
        self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.mainToolBar.setObjectName("mainToolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.mainToolBar)
        self.statusBar = QStatusBar(self.mainwindow)
        self.statusBar.setObjectName("statusBar")
        self.mainwindow.setStatusBar(self.statusBar)
        self.toolBar = QToolBar(self.mainwindow)
        self.toolBar.setLayoutDirection(Qt.RightToLeft)
        self.toolBar.setStyleSheet("")
        self.toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toolBar.setObjectName("toolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.actionNotification = QAction(self.mainwindow)
        self.actionNotification.setCheckable(True)
        self.actionNotification.setChecked(False)
        self.actionNotification.setEnabled(True)
        icon6 = QIcon()
        icon6.addPixmap(QPixmap(":/images/notification.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionNotification.setIcon(icon6)
        self.actionNotification.setAutoRepeat(True)
        self.actionNotification.setVisible(True)
        self.actionNotification.setIconVisibleInMenu(False)
        self.actionNotification.setObjectName("actionNotification")
        self.actionNotification
        self.actionAdmin = QAction(self.mainwindow)
        # self.actionAdmin.setCheckable(True)
        icon7 = QIcon()
        icon7.addPixmap(QPixmap(":/images/admin.png"), QIcon.Normal, QIcon.Off)
        self.actionAdmin.setIcon(icon7)
        self.actionAdmin.setObjectName("actionAdmin")
        self.actionRefresh = QAction(self.mainwindow)
        icon8 = QIcon()
        icon8.addPixmap(QPixmap(":/images/refresh.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionRefresh.setIcon(icon8)
        self.actionRefresh.setObjectName("actionRefresh")
        self.actionHome = QAction(self.mainwindow)
        # self.actionHome.setCheckable(True)
        icon9 = QIcon()
        icon9.addPixmap(QPixmap(":/images/home.png"), QIcon.Normal, QIcon.Off)
        self.actionHome.setIcon(icon9)
        self.actionHome.setObjectName("actionHome")
        self.actionSettings = QAction(self.mainwindow)
        icon10 = QIcon()
        icon10.addPixmap(QPixmap(":/images/settings.png"), QIcon.Normal,
                         QIcon.Off)
        self.actionSettings.setIcon(icon10)
        self.actionSettings.setObjectName("actionRefresh")
        self.toolBar.addAction(self.actionNotification)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionAdmin)
        if ('Admin', True) in self.access:
            self.toolBar.addSeparator()
        else:
            self.actionAdmin.setVisible(False)
        self.toolBar.addAction(self.actionHome)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionSettings)
        ##retranslates
        self.mainwindow.setWindowTitle(
            QApplication.translate("MainWindow", settings.company, None,
                                   QApplication.UnicodeUTF8))
        self.label_10.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">BILLING</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_11.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">EMPLOYEE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_12.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">MENU</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_13.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">REPORT</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_14.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">WASTE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_9.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">INVENTORY</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.inventory_frame_1.setToolTip(
            QApplication.translate("MainWindow", "Go to the Inventory Tab",
                                   None, QApplication.UnicodeUTF8))
        self.billing_frame_2.setToolTip(
            QApplication.translate("MainWindow", "Go to the Billing Tab", None,
                                   QApplication.UnicodeUTF8))
        self.employee_frame_3.setToolTip(
            QApplication.translate("MainWindow", "Go to the Employee Tab",
                                   None, QApplication.UnicodeUTF8))
        self.menu_frame_4.setToolTip(
            QApplication.translate("MainWindow", "Go to the Menu Tab", None,
                                   QApplication.UnicodeUTF8))
        self.report_frame_5.setToolTip(
            QApplication.translate("MainWindow", "Go to the Report Tab", None,
                                   QApplication.UnicodeUTF8))
        self.waste_frame_6.setToolTip(
            QApplication.translate("MainWindow", "Go to the Waste Tab", None,
                                   QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(
            QApplication.translate("MainWindow", "toolBar", None,
                                   QApplication.UnicodeUTF8))
        self.actionNotification.setText("&&Notification")
        # QApplication.translate("MainWindow", "&Notification", None, QApplication.UnicodeUTF8))
        self.actionNotification.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to see new notifications", None,
                                   QApplication.UnicodeUTF8))
        # self.actionNotification.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+N", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setText('&&Admin')
        # QApplication.translate("MainWindow", "Admin", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to go to admin interface", None,
                                   QApplication.UnicodeUTF8))
        # self.actionAdmin.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+A", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setText("&&Refresh")
        # QApplication.translate("MainWindow", "Refresh", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setToolTip(
            QApplication.translate("MainWindow",
                                   "refreshes the data from the server", None,
                                   QApplication.UnicodeUTF8))
        # self.actionRefresh.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+R", None, QApplication.UnicodeUTF8))
        self.actionHome.setText('&&Home')
        # QApplication.translate("MainWindow", "Home", None, QApplication.UnicodeUTF8))
        self.actionHome.setToolTip(
            QApplication.translate("MainWindow", "Go back to the home screen",
                                   None, QApplication.UnicodeUTF8))
        self.actionSettings.setText('&&Settings')
        # QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setToolTip(
            QApplication.translate("MainWindow", "Go to the settings panel",
                                   None, QApplication.UnicodeUTF8))
        # self.actionHome.setShortcut(
        #     QApplication.translate("MainWindow", "Ctrl+Shift+H", None, QApplication.UnicodeUTF8))
        self.stackedWidget.setCurrentIndex(1)
        self.main_tabWidget.setCurrentIndex(0)

        self.ob = self.main_tabWidget.tabBar()
        # self.add_tool_tip(self.ob) todo avoided due to segmentation fault error, left for future fixes
        self.tb = EventHandlerForTabBar()
        self.ob.installEventFilter(self.tb)

        QMetaObject.connectSlotsByName(self.mainwindow)
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)
Beispiel #29
0
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)
Beispiel #30
0
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())
    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
Beispiel #32
0
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 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)