class TooltipPositioningWithArrow(TooltipPositioning):
    ARROW_MARGIN = 7
    ARROW_SIZE = 11
    ARROW_ODD_SIZE = 15

    def _getTopOrBottomArrow(self, alignment, tooltip, main_window):
        arrow_alignment = TooltipAlignment.mapToMainWindow(tooltip.hoveredWidget(), main_window).x() - alignment + \
              tooltip.hoveredWidget().width() / 2 - self.ARROW_ODD_SIZE / 2

        if arrow_alignment > tooltip.widget().width():
            arrow_alignment = tooltip.widget().width() - self.ARROW_ODD_SIZE

        self._arrow = QWidget()
        self._arrow.setLayout(self._getTopOrBottomArrowLayout(arrow_alignment))

        self._label_arrow = QLabel()
        self._label_arrow.setStyleSheet(
            self._getArrowStylesheet(tooltip.color()))
        self._label_arrow.setFixedWidth(self.ARROW_ODD_SIZE)
        self._label_arrow.setFixedHeight(self.ARROW_SIZE)

        self._arrow.layout().addWidget(self._label_arrow)
        return self._arrow

    def _getTopOrBottomArrowLayout(self, arrow_alignment):
        self._arrow_layout = QHBoxLayout()
        self._arrow_layout.setAlignment(Qt.AlignLeft)
        self._arrow_layout.setContentsMargins(arrow_alignment, 0, 0, 0)
        return self._arrow_layout

    def _getLeftOrRightArrow(self, alignment, tooltip, main_window):
        arrow_alignment = TooltipAlignment.mapToMainWindow(tooltip.hoveredWidget(), main_window).y() \
              - alignment + tooltip.hoveredWidget().height() / 2 - self.ARROW_ODD_SIZE / 2

        if arrow_alignment > tooltip.widget().height():
            arrow_alignment = tooltip.widget().height() - self.ARROW_ODD_SIZE

        self._arrow = QWidget()
        self._arrow.setLayout(self._getLeftOrRightArrowLayout(arrow_alignment))

        self._label_arrow = QLabel()
        self._label_arrow.setStyleSheet(
            self._getArrowStylesheet(tooltip.color()))
        self._label_arrow.setFixedWidth(self.ARROW_SIZE)
        self._label_arrow.setFixedHeight(self.ARROW_ODD_SIZE)

        self._arrow.layout().addWidget(self._label_arrow)
        return self._arrow

    def _getLeftOrRightArrowLayout(self, arrow_alignment):
        self._arrow_layout = QVBoxLayout()
        self._arrow_layout.setAlignment(Qt.AlignTop)
        self._arrow_layout.setContentsMargins(0, arrow_alignment, 0, 0)
        return self._arrow_layout

    def _getArrowStylesheet(self, color="rgb(255, 255, 255)"):
        raise NotImplementedError("Subclass responsibility")

    def showTooltip(self, tooltip, align, main_window):
        raise NotImplementedError("Subclass responsibility")
Exemple #2
0
    class CommandDocsWidget(QScrollArea):
        def __init__(self, command, parent=None):
            super(CommandDocsWidget, self).__init__(parent)
            self.command = CommandDocsParser.parse(command)
            self._setupUi()
    
        def _setupUi(self):
            self.setWidgetResizable(True)
            
            self.docsWidget = QWidget()
            docsLayout = QVBoxLayout()
            self.docsWidget.setLayout(docsLayout)

            lblCmdName = QLabel("<h1>{0}</h1>".format(self.command.name))
            docsLayout.addWidget(lblCmdName)
            
            lblDesc = QLabel(self.command.description)
            docsLayout.addWidget(lblDesc)

            self.flagsWidget = QWidget()
            self.flagsWidget.setLayout(QVBoxLayout())
            docsLayout.addWidget(self.flagsWidget)
    
            self.setWidget(self.docsWidget)
            
            self.refreshDocs()
            
        def refreshDocs(self, modes=None):
            if modes:
                docsLayout = self.docsWidget.layout()
                docsLayout.removeWidget(self.flagsWidget)
                self.flagsWidget.hide()
                self.flagsWidget.deleteLater()
                self.flagsWidget = QWidget()
                self.flagsWidget.setLayout(QVBoxLayout())
                docsLayout.addWidget(self.flagsWidget)
                flags = []
                for mode in modes:
                    for name in self.command.modes[mode]:
                        flags.append(self.command.flags[name])
            else:
                flags = self.command.flags.values()
                docsLayout = self.docsWidget.layout()
                docsLayout.removeWidget(self.flagsWidget)
                self.flagsWidget.hide()
                self.flagsWidget.deleteLater()
                self.flagsWidget = QWidget()
                self.flagsWidget.setLayout(QVBoxLayout())
                docsLayout.addWidget(self.flagsWidget)

            flagsLayout = self.flagsWidget.layout()
            
            for flag in flags:
                lblFlag = QLabel("<h2>{0.longName} - {0.shortName} - {0.type}</h2>".format(flag))
                flagsLayout.addWidget(lblFlag)
                lblModes = QLabel("{0}".format(', '.join(flag.modes) if flag.modes else "Undefined"))
                flagsLayout.addWidget(lblModes)
                lblFlagDesc = QLabel(flag.description)
                flagsLayout.addWidget(lblFlagDesc)
 def setupUi(self):
     centralWidget = QWidget(self)
     centralWidget.setLayout(QVBoxLayout(centralWidget))
     self.view = QTableView(centralWidget)
     self.view.setSortingEnabled(True)
     centralWidget.layout().addWidget(self.view)
     self.searchBox = QLineEdit(centralWidget)
     centralWidget.layout().addWidget(self.searchBox)
     self.setCentralWidget(centralWidget)
     self.searchBox.setFocus()
 def setupUi(self):
     centralWidget = QWidget(self)
     centralWidget.setLayout(QVBoxLayout(centralWidget))
     self.view = QTableView(centralWidget)
     self.view.setSortingEnabled(True)
     centralWidget.layout().addWidget(self.view)
     self.searchBox = QLineEdit(centralWidget)
     centralWidget.layout().addWidget(self.searchBox)
     self.setCentralWidget(centralWidget)
     self.searchBox.setFocus()
Exemple #5
0
 def __init__(self, parent=None):
     QMainWindow.__init__(self, parent)
     self.setWindowTitle('Validation example')
     central = QWidget(self)
     central.setLayout(QVBoxLayout(central))
     self.edit = QLineEdit(central)
     central.layout().addWidget(self.edit)
     # create a validator
     edit_validator = QDoubleValidator(self.edit)
     # and add it to the edito widget
     self.edit.setValidator(edit_validator)
     self.setCentralWidget(central)
     self.edit.returnPressed.connect(self.do_it)
 def __init__(self, parent=None):
     QMainWindow.__init__(self, parent)
     self.setWindowTitle('Validation example')
     central = QWidget(self)
     central.setLayout(QVBoxLayout(central))
     self.edit = QLineEdit(central)
     central.layout().addWidget(self.edit)
     # create a validator
     edit_validator = QDoubleValidator(self.edit)
     # and add it to the edito widget
     self.edit.setValidator(edit_validator)
     self.setCentralWidget(central)
     self.edit.returnPressed.connect(self.do_it)
Exemple #7
0
    def __init__(self):
        generic.GenericGui.__init__(self)
        window = QWidget()
        window.setWindowTitle('quichem-pyside')

        self.compiler_view = QListWidget()
        self.compiler_view.currentRowChanged.connect(self.show_source)
        self.stacked_widget = QStackedWidget()
        self.stacked_widget.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)
        self.edit = QLineEdit()
        self.edit.setPlaceholderText('Type quichem input...')
        self.edit.textChanged.connect(self.change_value)
        self.view = QWebView()
        self.view.page().mainFrame().setScrollBarPolicy(Qt.Vertical,
                                                        Qt.ScrollBarAlwaysOff)
        self.view.page().action(QWebPage.Reload).setVisible(False)
        self.view.setMaximumHeight(0)
        self.view.setUrl('qrc:/web/page.html')
        self.view.setZoomFactor(2)
        self.view.page().mainFrame().contentsSizeChanged.connect(
            self._resize_view)
        # For debugging JS:
        ## from PySide.QtWebKit import QWebSettings
        ## QWebSettings.globalSettings().setAttribute(
        ##     QWebSettings.DeveloperExtrasEnabled, True)

        button_image = QPushButton('Copy as Image')
        button_image.clicked.connect(self.set_clipboard_image)
        button_image.setToolTip('Then paste into any graphics program')
        button_word = QPushButton('Copy as MS Word Equation')
        button_word.clicked.connect(self.set_clipboard_word)
        button_html = QPushButton('Copy as Formatted Text')
        button_html.clicked.connect(self.set_clipboard_html)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(button_image)
        button_layout.addWidget(button_word)
        button_layout.addWidget(button_html)
        source_layout = QHBoxLayout()
        source_layout.addWidget(self.compiler_view)
        source_layout.addWidget(self.stacked_widget, 1)
        QVBoxLayout(window)
        window.layout().addWidget(self.edit)
        window.layout().addWidget(self.view)
        window.layout().addLayout(button_layout)
        window.layout().addWidget(line)
        window.layout().addLayout(source_layout, 1)

        window.show()
        window.resize(window.minimumWidth(), window.height())
        # To prevent garbage collection of internal Qt object.
        self._window = window
Exemple #8
0
 def make_source(self, name):
     self.compiler_view.addItem(name)
     self.compiler_view.setCurrentRow(0)
     scrollbar_width = QApplication.style().pixelMetric(
         QStyle.PM_ScrollBarExtent)
     self.compiler_view.setMaximumWidth(
         self.compiler_view.sizeHintForColumn(0) + scrollbar_width + 16)
     page = QWidget()
     QHBoxLayout(page)
     page.layout().setContentsMargins(*(0,) * 4)
     source = QTextEdit()
     source.setStyleSheet('min-width: 0; min-height: 0')
     source.setReadOnly(True)
     QVBoxLayout(source)
     button = QPushButton('Copy')
     button.clicked.connect(functools.partial(self.set_clipboard, source))
     page.layout().addWidget(source)
     source.layout().addWidget(button, 0, Qt.AlignRight | Qt.AlignBottom)
     self.stacked_widget.addWidget(page)
     return source
 def __init__(self):
     super(HighwayAnalyzeWidget,self).__init__()
     self.averageSimulationTime = 325.0
     mainLayout = QVBoxLayout()
     mainLayout.setAlignment(Qt.AlignTop|Qt.AlignHCenter)
     mainLayout.setSpacing(0)
     self.setLayout(mainLayout)
     topWidget = QWidget()
     self.topLayout = QHBoxLayout()
     self.topLayout.setSpacing(0)
     topWidget.setLayout(self.topLayout)
     topLeftWidget = QWidget()
     self.topLeftLayout = QVBoxLayout()
     topLeftWidget.setLayout(self.topLeftLayout)
     self.setupTopGroup()
     self.setupFilterGroup()
     self.topLayout.addWidget(topLeftWidget)
     self.layout().addWidget(topWidget)
     # Button and log
     buttonAndLogWidget = QWidget()
     buttonAndLogWidget.setLayout(QVBoxLayout())
     # Analyze the results BUTTON
     self.analyzeResultsButton = QPushButton('Analyze the results')
     self.analyzeResultsButton.clicked.connect(self.analyzeResults)
     self.analyzeResultsButton.setEnabled(False)
     buttonAndLogWidget.layout().addWidget(self.analyzeResultsButton)
     # LOG
     self.logText = QTextBrowser()
     self.logText.setFont(QFont('Century Gothic', 7))
     self.logText.setWordWrapMode(QTextOption.NoWrap)
     buttonAndLogWidget.layout().addWidget(self.logText)
     self.topLayout.addWidget(buttonAndLogWidget)
     self.results = []
     self.logFile = os.path.join(self.resultsPath(), 'analyze_'+os.uname()[1]+'.log')
     # Image
     self.picLabel = QLabel()
     self.picLabel.setAlignment(Qt.AlignHCenter)
     #self.picLabel.resize(800,600)
     self.picLabel.setMinimumSize(800,600)
     self.layout().addWidget(self.picLabel)
    def setup_ui(self):
        splitter = QSplitter(self)
        left = QWidget(splitter)
        left.setLayout(QVBoxLayout(left))
        left.layout().addWidget(QLabel('QTableView', left))
        tableview = QTableView(left)
        tableview.setModel(TableModel(tableview))
        left.layout().addWidget(tableview)
        splitter.addWidget(left)
        right = QWidget(splitter)
        right.setLayout(QVBoxLayout(right))
        right.layout().addWidget(QLabel('QTableWidget', right))
        # create a table widget for DATA
        tablewidget = QTableWidget(len(DATA), len(DATA[1]), right)
        right.layout().addWidget(tablewidget)
        splitter.addWidget(right)
        self.setCentralWidget(splitter)

        # add tablewidget data
        self.add_data(tablewidget)
    def setup_ui(self):
        splitter = QSplitter(self)
        left = QWidget(splitter)
        left.setLayout(QVBoxLayout(left))
        left.layout().addWidget(QLabel('QTableView', left))
        tableview = QTableView(left)
        tableview.setModel(TableModel(tableview))
        left.layout().addWidget(tableview)
        splitter.addWidget(left)
        right = QWidget(splitter)
        right.setLayout(QVBoxLayout(right))
        right.layout().addWidget(QLabel('QTableWidget', right))
        # create a table widget for DATA
        tablewidget = QTableWidget(len(DATA), len(DATA[1]), right)
        right.layout().addWidget(tablewidget)
        splitter.addWidget(right)
        self.setCentralWidget(splitter)

        # add tablewidget data
        self.add_data(tablewidget)
Exemple #12
0

def redirect_to_permission_page():
    QDesktopServices.openUrl(get_permission_url())
    quickstart(auth_server)


def shoot():
    if (not isTokenCollected()):
        redirect_to_permission_page()

    #taking the screenshot
    filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')
    p = QPixmap.grabWindow(QApplication.desktop().winId())
    p.save(filename, 'jpg')
    upload_file_to_drive(filename)


def upload_file_to_drive(fname):
    service = get_drive_service()
    insert_file(service, fname, 'SHTR SHOT', None, 'image/jpg', fname)


widget.layout().addWidget(QPushButton('Setup Google Drive', clicked=shoot))
dispatcher.connect(receive_verification_code)

widget.show()

#enter Qt App main loop
app.exec_()
sys.exit()
Exemple #13
0
    save_credentials(sender)
    auth_server.stop_server()


def redirect_to_permission_page():
    QDesktopServices.openUrl(get_permission_url())
    quickstart(auth_server)

def shoot():
    if( not isTokenCollected()):
        redirect_to_permission_page()

    #taking the screenshot
    filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')
    p = QPixmap.grabWindow(QApplication.desktop().winId())
    p.save(filename, 'jpg')
    upload_file_to_drive(filename)

def upload_file_to_drive(fname):
    service = get_drive_service()
    insert_file(service, fname, 'SHTR SHOT', None, 'image/jpg', fname)

widget.layout().addWidget(QPushButton('Setup Google Drive', clicked=shoot))
dispatcher.connect(receive_verification_code)

widget.show()


#enter Qt App main loop
app.exec_()
sys.exit()
Exemple #14
0
    class CommandDocsWidget(QScrollArea):
        def __init__(self, command, parent=None):
            super(CommandDocsWidget, self).__init__(parent)
            self.command = CommandDocsParser.parse(command)
            self._setupUi()

        def _setupUi(self):
            self.setWidgetResizable(True)

            self.docsWidget = QWidget()
            docsLayout = QVBoxLayout()
            self.docsWidget.setLayout(docsLayout)

            lblCmdName = QLabel("<h1>{0}</h1>".format(self.command.name))
            docsLayout.addWidget(lblCmdName)

            lblDesc = QLabel(self.command.description)
            docsLayout.addWidget(lblDesc)

            self.flagsWidget = QWidget()
            self.flagsWidget.setLayout(QVBoxLayout())
            docsLayout.addWidget(self.flagsWidget)

            self.setWidget(self.docsWidget)

            self.refreshDocs()

        def refreshDocs(self, modes=None):
            if modes:
                docsLayout = self.docsWidget.layout()
                docsLayout.removeWidget(self.flagsWidget)
                self.flagsWidget.hide()
                self.flagsWidget.deleteLater()
                self.flagsWidget = QWidget()
                self.flagsWidget.setLayout(QVBoxLayout())
                docsLayout.addWidget(self.flagsWidget)
                flags = []
                for mode in modes:
                    for name in self.command.modes[mode]:
                        flags.append(self.command.flags[name])
            else:
                flags = self.command.flags.values()
                docsLayout = self.docsWidget.layout()
                docsLayout.removeWidget(self.flagsWidget)
                self.flagsWidget.hide()
                self.flagsWidget.deleteLater()
                self.flagsWidget = QWidget()
                self.flagsWidget.setLayout(QVBoxLayout())
                docsLayout.addWidget(self.flagsWidget)

            flagsLayout = self.flagsWidget.layout()

            for flag in flags:
                lblFlag = QLabel(
                    "<h2>{0.longName} - {0.shortName} - {0.type}</h2>".format(
                        flag))
                flagsLayout.addWidget(lblFlag)
                lblModes = QLabel("{0}".format(
                    ', '.join(flag.modes) if flag.modes else "Undefined"))
                flagsLayout.addWidget(lblModes)
                lblFlagDesc = QLabel(flag.description)
                flagsLayout.addWidget(lblFlagDesc)
    def __init__(self):
        QMainWindow.__init__(self)

        # the user interface, consisting of a progress bar above a plain
        # text edit, which logs all actions.
        container = QWidget(self)
        container.setLayout(QVBoxLayout(container))
        self.setCentralWidget(container)
        progressbar = QProgressBar(container)
        container.layout().addWidget(progressbar)
        log = QPlainTextEdit(container)
        container.layout().addWidget(log)

        # the actual worker thread
        counter = Counter(100, self)

        # an action to quit the windows
        exit = QAction(QIcon.fromTheme('application-exit'), 'exit', self)

        # add two actions to start and stop the worker to the toolbar of the
        # main window
        start_counting = QAction(QIcon.fromTheme('media-playback-start'),
                                 'Start counting', self)
        stop_counting = QAction(QIcon.fromTheme('media-playback-stop'),
                                'Stop counting', self)
        # initially no counter runs, so we can disable the stop action
        stop_counting.setEnabled(False)

        # add all actions to a toolbar
        actions = self.addToolBar('Actions')
        actions.addAction(exit)
        actions.addSeparator()
        actions.addAction(start_counting)
        actions.addAction(stop_counting)

        # quit the application, if the quit action is triggered
        exit.triggered.connect(QApplication.instance().quit)

        # start and stop the counter, if the corresponding actions are
        # triggered.
        start_counting.triggered.connect(counter.start)
        stop_counting.triggered.connect(counter.stop)

        # adjust the minimum and the maximum of the progress bar, if
        # necessary.  Not really required in this snippet, but added for the
        # purpose of demonstrating it
        counter.minimumChanged.connect(progressbar.setMinimum)
        counter.maximumChanged.connect(progressbar.setMaximum)

        # switch the enabled states of the actions according to whether the
        # worker is running or not
        counter.started.connect(partial(start_counting.setEnabled, False))
        counter.started.connect(partial(stop_counting.setEnabled, True))
        counter.finished.connect(partial(start_counting.setEnabled, True))
        counter.finished.connect(partial(stop_counting.setEnabled, False))

        # update the progess bar continuously
        counter.progress.connect(progressbar.setValue)

        # log all actions in our logging widget
        counter.started.connect(
            partial(self.statusBar().showMessage, 'Counting'))
        counter.finished.connect(
            partial(self.statusBar().showMessage, 'Done'))
        # log a forced stop
        stop_counting.triggered.connect(
            partial(log.appendPlainText, 'Stopped'))
        # log all counted values
        counter.progress.connect(lambda v: log.appendPlainText(str(v)))

        # and finally show the current state in the status bar.
        counter.started.connect(partial(log.appendPlainText, 'Counting'))
        counter.finished.connect(partial(log.appendPlainText, 'Done'))
 def setupFilterGroup(self):
     filterGroup = QGroupBox('Filter the results')
     filterGroupLayout = QVBoxLayout()
     filterGroupLayout.setSpacing(0)
     filterGroupLayout.setAlignment(Qt.AlignTop)
     # Distribution Model
     self.filterDistribution = SimpleComboboxOption('dis','Speed Distribution Model',3, True, 'Uniform','Exponential','Normal','Log Normal')
     filterGroupLayout.addWidget(self.filterDistribution)
     self.filterDistribution.setVisible(False)
     # Number of results per point
     self.filterNb = SimpleSpinOption('simuNbMin', 'Minimum results for a given setting', 10, integer=True, checkable=True)
     self.filterNb.checkBox.setChecked(True)
     filterGroupLayout.addWidget(self.filterNb)
     # Filter the date
     dateWidget = QWidget()
     dateWidget.setLayout(QHBoxLayout())
     self.filterDate = QCheckBox('After')
     self.filterDate.setChecked(QSettings().value('filterDate','0')=='1')
     dateWidget.layout().addWidget(self.filterDate)
     self.filterDateYear = QComboBox()
     for m in xrange(2010,2012):
         self.filterDateYear.addItem(str(m))
     self.filterDateYear.setCurrentIndex(int(QSettings().value('dateYear', 1)))
     dateWidget.layout().addWidget(self.filterDateYear)
     dateWidget.layout().addWidget(QLabel('Year'))
     self.filterDateMonth = QComboBox()
     for m in xrange(1,13):
         self.filterDateMonth.addItem(str(m))
     self.filterDateMonth.setCurrentIndex(int(QSettings().value('dateMonth', 4)))
     dateWidget.layout().addWidget(self.filterDateMonth)
     dateWidget.layout().addWidget(QLabel('Month'))
     self.filterDateDay = QComboBox()
     for d in xrange(1,32):
         self.filterDateDay.addItem(str(d))
     self.filterDateDay.setCurrentIndex(int(QSettings().value('dateDay', 0)))
     dateWidget.layout().addWidget(self.filterDateDay)
     dateWidget.layout().addWidget(QLabel('Day'))
     filterGroupLayout.addWidget(dateWidget)
     filterGroup.setLayout(filterGroupLayout)
     self.topLeftLayout.addWidget(filterGroup)
     # Filter the scenario
     self.filterScenar = SimpleComboboxOption('scenar','Scenario',1, True, 'vanet-highway-test-thomas','vanet-highway-scenario2')
     filterGroupLayout.addWidget(self.filterScenar)
     # Filter gap
     self.filterGap = SimpleSpinOption('avgdistanalyze','Average Distance (m)',100, checkable=True)
     filterGroupLayout.addWidget(self.filterGap)
Exemple #17
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
Exemple #18
0
    def __init__(self):
        QMainWindow.__init__(self)

        # the user interface, consisting of a progress bar above a plain
        # text edit, which logs all actions.
        container = QWidget(self)
        container.setLayout(QVBoxLayout(container))
        self.setCentralWidget(container)
        progressbar = QProgressBar(container)
        container.layout().addWidget(progressbar)
        log = QPlainTextEdit(container)
        container.layout().addWidget(log)

        # the actual worker thread
        counter = Counter(100, self)

        # an action to quit the windows
        exit = QAction(QIcon.fromTheme('application-exit'), 'exit', self)

        # add two actions to start and stop the worker to the toolbar of the
        # main window
        start_counting = QAction(QIcon.fromTheme('media-playback-start'),
                                 'Start counting', self)
        stop_counting = QAction(QIcon.fromTheme('media-playback-stop'),
                                'Stop counting', self)
        # initially no counter runs, so we can disable the stop action
        stop_counting.setEnabled(False)

        # add all actions to a toolbar
        actions = self.addToolBar('Actions')
        actions.addAction(exit)
        actions.addSeparator()
        actions.addAction(start_counting)
        actions.addAction(stop_counting)

        # quit the application, if the quit action is triggered
        exit.triggered.connect(QApplication.instance().quit)

        # start and stop the counter, if the corresponding actions are
        # triggered.
        start_counting.triggered.connect(counter.start)
        stop_counting.triggered.connect(counter.stop)

        # adjust the minimum and the maximum of the progress bar, if
        # necessary.  Not really required in this snippet, but added for the
        # purpose of demonstrating it
        counter.minimumChanged.connect(progressbar.setMinimum)
        counter.maximumChanged.connect(progressbar.setMaximum)

        # switch the enabled states of the actions according to whether the
        # worker is running or not
        counter.started.connect(partial(start_counting.setEnabled, False))
        counter.started.connect(partial(stop_counting.setEnabled, True))
        counter.finished.connect(partial(start_counting.setEnabled, True))
        counter.finished.connect(partial(stop_counting.setEnabled, False))

        # update the progess bar continuously
        counter.progress.connect(progressbar.setValue)

        # log all actions in our logging widget
        counter.started.connect(
            partial(self.statusBar().showMessage, 'Counting'))
        counter.finished.connect(partial(self.statusBar().showMessage, 'Done'))
        # log a forced stop
        stop_counting.triggered.connect(partial(log.appendPlainText,
                                                'Stopped'))
        # log all counted values
        counter.progress.connect(lambda v: log.appendPlainText(str(v)))

        # and finally show the current state in the status bar.
        counter.started.connect(partial(log.appendPlainText, 'Counting'))
        counter.finished.connect(partial(log.appendPlainText, 'Done'))
Exemple #19
0
 def test_set_layout_succeeding(self):
     parent = QWidget()
     ChildAdder.add(QHBoxLayout(), 'fred', parent)
     self.assertTrue(isinstance(parent.layout(), QHBoxLayout))
class PointsWidget(QWidget):
	"""
	PointsWidget
	"""

	activeLandmarkChanged = Signal(int)
	landmarkDeleted = Signal(int)

	def __init__(self):
		super(PointsWidget, self).__init__()

		self.landmarkWidgets = []
		self.activeIndex = 0

		self.scrollArea = QScrollArea(self)
		self.scrollArea.setFrameShape(QFrame.NoFrame)
		self.scrollArea.setAutoFillBackground(False)
		self.scrollArea.setAttribute(Qt.WA_TranslucentBackground)
		self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
		self.scrollArea.setWidgetResizable(True)

		landmarkLocationsLayout = QGridLayout()
		landmarkLocationsLayout.setSpacing(0)
		landmarkLocationsLayout.setContentsMargins(0, 0, 0, 0)
		landmarkLocationsLayout.setAlignment(Qt.AlignTop)

		self.landmarkLocationsWidget = QWidget()
		Style.styleWidgetForTab(self.landmarkLocationsWidget)
		self.landmarkLocationsWidget.setLayout(landmarkLocationsLayout)
		self.scrollArea.setWidget(self.landmarkLocationsWidget)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.addWidget(self.scrollArea)
		self.setLayout(layout)

	@Slot(list)
	def setPoints(self, points):
		self._clearLandmarkWidgets()
		layout = self.landmarkLocationsWidget.layout()
		for index in range(len(points)):
			landmarkWidget = LandmarkLocationWidget()
			landmarkWidget.setIndex(index)
			landmarkWidget.active = (index == self.activeIndex)
			landmarkWidget.activated.connect(self.activateLandmark)
			landmarkWidget.deleted.connect(self.deleteLandmark)
			landmarkWidget.setLandmarkSet(points[index])
			layout.addWidget(landmarkWidget, index, 0)
			self.landmarkWidgets.append(landmarkWidget)

	def _clearLandmarkWidgets(self):
		layout = self.landmarkLocationsWidget.layout()
		for widget in self.landmarkWidgets:
			widget.activated.disconnect()
			layout.removeWidget(widget)
			widget.deleteLater()
		self.landmarkWidgets = []

	@Slot(int, object)
	def activateLandmark(self, index, state):
		if not state:
			self.activeIndex = len(self.landmarkWidgets)
		else:
			self.activeIndex = index
		self.activeLandmarkChanged.emit(self.activeIndex)

	@Slot(int)
	def deleteLandmark(self, index):
		self.activateLandmark(index, False)
		self.landmarkDeleted.emit(index)
	def _getHorizontalContainerFor(self, tooltip, main_window):
		container = QWidget(main_window)
		container.setLayout(QHBoxLayout())
		container.layout().setContentsMargins(0, 0, 0, 0)
		container.layout().setSpacing(0)
		return container