Пример #1
0
class Annotation(QGraphicsWidget):
    """Base class for annotations in the canvas scheme.
    """
    def __init__(self, parent=None, **kwargs):
        QGraphicsWidget.__init__(self, parent, **kwargs)

    if qVersion() < "4.7":
        geometryChanged = Signal()

        def setGeometry(self, rect):
            QGraphicsWidget.setGeometry(self, rect)
            self.geometryChanged.emit()
Пример #2
0
class GuiTestRunner(QObject, TestRunner):
    evaluate_started = Signal(str)
    evaluate_finished = Signal()

    def __init__(self):
        QObject.__init__(self)
        TestRunner.__init__(self)
        self.verdict = None
        self.launcher = None
        self.launcher_kwargs = {}
        self.run_error = False

    def evaluate(self, build_info, allow_back=False):
        try:
            self.launcher = self.create_launcher(build_info)
            self.launcher.start(**self.launcher_kwargs)
            build_info.update_from_app_info(self.launcher.get_app_info())
        except Exception, exc:
            self.run_error = True
            self.evaluate_started.emit(str(exc))
        else:
Пример #3
0
class Messenger(QtCore.QObject):
    throw = Signal(object)

    def __init__(self):
        QtCore.QObject.__init__(self)
        self.throw.connect(self.show_error)

    @Slot(object)
    def show_error(self, err):
        msg, tb = printErrorToConsole(err)  #,add=" somewhere in Qt")
        for f in Fluxi._fluxis.values():
            f.logError(msg=msg, details=tb)
Пример #4
0
class PlotPanTool(PlotTool):
    """
    Pan/translate tool.
    """
    panStarted = Signal()
    translated = Signal(QPointF)
    panFinished = Signal()

    def __init__(self, parent=None, autoPan=True, **kwargs):
        super().__init__(parent, **kwargs)
        self.__autopan = autoPan

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.panStarted.emit()
            event.accept()
            return True
        else:
            return False

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            viewbox = self.viewBox()
            delta = (viewbox.mapToView(event.pos()) -
                     viewbox.mapToView(event.lastPos()))
            if self.__autopan:
                viewbox.translateBy(-delta / 2)
            self.translated.emit(-delta / 2)
            event.accept()
            return True
        else:
            return False

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.panFinished.emit()
            event.accept()
            return True
        else:
            return False
Пример #5
0
class Comunicate(QObject):
    sig = Signal(str)
    img = Signal(str)
    op = Signal(str)
    msg = Signal(str)
    mBox = Signal(str)
    mBoxEr = Signal(str)
Пример #6
0
class TraitWidget(QWidget):
    """
	@brief Grundlage der Widgets für alle Eigenschaften.
	"""

    maxTraitChanged = Signal(int)
    hideReasonChanged = Signal(str, str, str)

    def __init__(self, template, character, parent=None):
        super(TraitWidget, self).__init__(parent)

        self._character = character
        self._storage = template

        # Wenn sich Spezies oder Powerstat ändert, kann sich der erlaubte Maximalwert ändern.
        self._character.powerstatChanged.connect(self.emitMaxTraitChanged)
        self._character.speciesChanged.connect(self.emitMaxTraitChanged)
        # Ändert sich alterskategorie oder die Ära, Wird ein paasendes Signal gesandt.
        self._character.eraChanged.connect(self.emitHideReasonChanged)
        self._character.ageChanged[str].connect(self.emitHideReasonChanged)
        self._character.speciesChanged.connect(self.emitHideReasonChanged)

    def emitMaxTraitChanged(self):
        """
		Sendet ein Signal aus, das als Wert das neue Maximum der Eigenschaften enthält.
		"""

        maxTrait = self._storage.maxTrait(self._character.species,
                                          self._character.powerstat)
        self.maxTraitChanged.emit(maxTrait)

    def emitHideReasonChanged(self):
        #Debug.debug(Config.getAge(self._character.age), self._character.era)
        #ageStr = Config.AGES[0]
        #if self._character.age < Config.AGE_ADULT:
        #ageStr = Config.AGES[1]
        ageStr = Config.getAge(self._character.age)
        eraStr = self._character.era
        self.hideReasonChanged.emit(self._character.species, ageStr, eraStr)
Пример #7
0
class GraphicsTextEdit(QGraphicsTextItem):
    #: Edit triggers
    NoEditTriggers, DoubleClicked = 0, 1

    editingFinished = Signal()
    editingStarted = Signal()

    documentSizeChanged = Signal()

    def __init__(self, *args, **kwargs):
        super(GraphicsTextEdit, self).__init__(*args, **kwargs)
        self.setTabChangesFocus(True)
        self._edittrigger = GraphicsTextEdit.DoubleClicked
        self._editing = False
        self.document().documentLayout().documentSizeChanged.connect(
            self.documentSizeChanged
        )

    def mouseDoubleClickEvent(self, event):
        super(GraphicsTextEdit, self).mouseDoubleClickEvent(event)
        if self._edittrigger == GraphicsTextEdit.DoubleClicked:
            self._start()

    def focusOutEvent(self, event):
        super(GraphicsTextEdit, self).focusOutEvent(event)

        if self._editing:
            self._end()

    def _start(self):
        self._editing = True
        self.setTextInteractionFlags(Qt.TextEditorInteraction)
        self.setFocus(Qt.MouseFocusReason)
        self.editingStarted.emit()

    def _end(self):
        self._editing = False
        self.setTextInteractionFlags(Qt.NoTextInteraction)
        self.editingFinished.emit()
Пример #8
0
class SchemeArrowAnnotation(BaseSchemeAnnotation):
    """
    An arrow annotation in the scheme.
    """

    color_changed = Signal(unicode)

    def __init__(self,
                 start_pos,
                 end_pos,
                 color="red",
                 anchor=None,
                 parent=None):
        BaseSchemeAnnotation.__init__(self, parent)
        self.__start_pos = start_pos
        self.__end_pos = end_pos
        self.__color = color
        self.__anchor = anchor

    def set_line(self, start_pos, end_pos):
        """
        Set arrow lines start and end position (``(x, y)`` tuples).
        """
        if self.__start_pos != start_pos or self.__end_pos != end_pos:
            self.__start_pos = start_pos
            self.__end_pos = end_pos
            self.geometry_changed.emit()

    def start_pos(self):
        """
        Start position of the arrow (base point).
        """
        return self.__start_pos

    start_pos = Property(tuple, fget=start_pos)

    def end_pos(self):
        """
        End position of the arrow (arrow head points toward the end).
        """
        return self.__end_pos

    end_pos = Property(tuple, fget=end_pos)

    def set_geometry(self, (start_pos, end_pos)):
        """
        Set the geometry of the arrow as a start and end position tuples
        (e.g. ``set_geometry(((0, 0), (100, 0))``).

        """
        self.set_line(start_pos, end_pos)
Пример #9
0
class FindAndReplaceDlg(QDialog, ui_findandreplacedlg.Ui_FindAndReplaceDlg):

    find = Signal(QString, bool, bool, bool, bool, bool)
    replace = Signal(QString, QString, bool, bool, bool, bool, bool)

    def __init__(self, parent=None):
        super(FindAndReplaceDlg, self).__init__(parent)
        self.setupUi(self)
        self.moreFrame.hide()
        self.layout().setSizeConstraint(QLayout.SetFixedSize)
        self.updateUi()

    @Slot(QString)
    def on_findLineEdit_textEdited(self, text):
        self.updateUi()

    @Slot()
    def on_findButton_clicked(self):
        self.find.emit(self.findLineEdit.text(), self.caseCheckBox.isChecked(),
                       self.wholeCheckBox.isChecked(),
                       self.backwardsCheckBox.isChecked(),
                       self.regexCheckBox.isChecked(),
                       self.ignoreNotesCheckBox.isChecked())

    @Slot()
    def on_replaceButton_clicked(self):
        self.replace.emit(self.findLineEdit.text(),
                          self.replaceLineEdit.text(),
                          self.caseCheckBox.isChecked(),
                          self.wholeCheckBox.isChecked(),
                          self.backwardsCheckBox.isChecked(),
                          self.regexCheckBox.isChecked(),
                          self.ignoreNotesCheckBox.isChecked())

    def updateUi(self):
        enable = not self.findLineEdit.text().isEmpty()
        self.findButton.setEnabled(enable)
        self.replaceButton.setEnabled(enable)
Пример #10
0
class GuiBuildDownloadManager(QObject, BuildDownloadManager):
    download_progress = Signal(object, int, int)
    download_started = Signal(object)
    download_finished = Signal(object, str)

    def __init__(self, destdir, **kwargs):
        QObject.__init__(self)
        BuildDownloadManager.__init__(self, None, destdir, **kwargs)

    def _download_started(self, task):
        self.download_started.emit(task)
        BuildDownloadManager._download_started(self, task)

    def _download_finished(self, task):
        try:
            self.download_finished.emit(task, task.get_dest())
        except RuntimeError:
            # in some cases, closing the application may destroy the
            # underlying c++ QObject, causing this signal to fail.
            # Skip this silently.
            pass
        BuildDownloadManager._download_finished(self, task)

    def focus_download(self, build_info):
        build_url, fname = self._extract_download_info(build_info)
        dest = self.get_dest(fname)
        build_info['build_path'] = dest
        # first, stop all downloads in background (except the one for this
        # build if any)
        self.cancel(cancel_if=lambda dl: dest != dl.get_dest())

        dl = self.download(build_url, fname)
        if dl:
            dl.set_progress(self.download_progress.emit)
        else:
            # file already downloaded.
            # emit the finished signal so bisection goes on
            self.download_finished.emit(None, dest)
Пример #11
0
class ToolButtonEventListener(QObject):
    """
    An event listener(filter) for :class:`QToolButtons`.
    """
    buttonLeftClicked = Signal(QToolButton)
    buttonRightClicked = Signal(QToolButton)
    buttonEnter = Signal(QToolButton)
    buttonLeave = Signal(QToolButton)

    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self.button_down = None
        self.button = None
        self.button_down_pos = None

    def eventFilter(self, obj, event):
        if not isinstance(obj, QToolButton):
            return False

        if event.type() == QEvent.MouseButtonPress:
            self.button = obj
            self.button_down = event.button()
            self.button_down_pos = event.pos()

        elif event.type() == QEvent.MouseButtonRelease:
            if self.button.underMouse():
                if event.button() == Qt.RightButton:
                    self.buttonRightClicked.emit(self.button)
                elif event.button() == Qt.LeftButton:
                    self.buttonLeftClicked.emit(self.button)

        elif event.type() == QEvent.Enter:
            self.buttonEnter.emit(obj)

        elif event.type() == QEvent.Leave:
            self.buttonLeave.emit(obj)

        return False
Пример #12
0
class TextStream(QObject):
    stream = Signal(str)
    flushed = Signal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent)

    @queued
    def write(self, string):
        self.stream.emit(string)

    @queued
    def writelines(self, lines):
        self.stream.emit("".join(lines))

    @queued
    def flush(self):
        self.flushed.emit()

    def customEvent(self, event):
        if event.type() == QueuedCallEvent.QueuedCall:
            event.call()
            event.accept()
Пример #13
0
class ColorParameters(QObject):
    changed = Signal()
    """
    Parameters for continuous objects.
    """
    def __init__(self, params, parent=None):
        QObject.__init__(self, parent)
        log_debug("Parameter object: %s" % id(params))
        self._color = params.color
        self._params = params

    def widget(self, parent):
        config = createForm("plot_param_color.ui", parent)
        setColor(config.color, self._color)
        config.selectColor.clicked.connect(self._changeColor)
        self._config = config
        return config

    @Slot()
    def _changeColor(self):
        if changeColor(self._config.color):
            self.color = getColor(self._config.color)

    @property
    def color(self):
        '''Color used for the rendering of the property.

        :returntype: `QColor`'''
        return self._color

    @color.setter
    def color(self, value):
        value = QColor(value)
        if self._color != value:
            self._color = value
            self._params.color = value
            self.changed.emit()

    @staticmethod
    def load(params, settings):
        log_debug("Loading with parameter object: %s" % id(params))
        color = QColor(settings.value("Color"))
        if not color.isValid():
            color = QColor(0, 0, 0)
        params.color = color

    @staticmethod
    def save(params, settings):
        settings.setValue("Color", params.color)
Пример #14
0
class GridWidget(QWidget):
    selectionChanged = Signal()

    def __init__(self, *args):
        super(GridWidget, self).__init__(*args)
        self.setLayout(QGridLayout())
        self.layout().setSizeConstraint(QGridLayout.SetMinAndMaxSize)
        self.__autoreflow = False

    def resizeEvent(self, event):
        super(GridWidget, self).resizeEvent(event)
        if self.__autoreflow:
            self.reflow(self.width())

    def appendWidget(self, widget):
        count = self.layout().count()
        ncol = self.layout().columnCount()
        self.layout().addWidget(widget, count // ncol, count % ncol)

    def count(self):
        return self.layout().count()

    def clear(self):
        for i in reversed(range(self.count())):
            item = self.layout().takeAt(i)
            if item.widget() is not None and item.widget().parent() is self:
                widget = item.widget()
                widget.setParent(None)
                widget.deleteLater()

    def reflow(self, width):
        grid = self.layout()

        items = [grid.itemAt(i) for i in range(grid.count())]
        sizes = [item.sizeHint() for item in items]
        wmax = reduce(max, (sh.width() for sh in sizes), 0)
        hspacing = grid.horizontalSpacing()
        left, _, right, _ = grid.getContentsMargins()

        # width >= wmax * ncols + (ncols - 1) * hspacing + left + right
        ncols = (width - left - right + hspacing) / (wmax + 1)
        ncols = max(1, math.floor(ncols))

        if ncols != grid.columnCount():
            for i in range(len(items) - 1, -1, -1):
                grid.takeAt(i)

            for i, item in enumerate(items):
                grid.addItem(item, i // ncols, i % ncols)
Пример #15
0
class GuiTestRunner(QObject, TestRunner):
    evaluate_started = Signal()
    evaluate_finished = Signal()

    def __init__(self):
        QObject.__init__(self)
        TestRunner.__init__(self)
        self.app_info = {}
        self.verdict = None
        self.launcher = None
        self.launcher_kwargs = {}

    def evaluate(self, build_info, allow_back=False):
        self.launcher = self.create_launcher(build_info)
        self.launcher.start(**self.launcher_kwargs)
        self.app_info = self.launcher.get_app_info()
        self.evaluate_started.emit()

    def finish(self, verdict):
        assert self.launcher
        self.launcher.stop()
        self.verdict = verdict
        self.evaluate_finished.emit()
        self.launcher = None
Пример #16
0
class Annotation(QGraphicsWidget):
    """Base class for annotations in the canvas scheme.
    """
    def __init__(self, parent=None, **kwargs):
        QGraphicsWidget.__init__(self, parent, **kwargs)

    if QT_VERSION < 0x40700:
        geometryChanged = Signal()

        def setGeometry(self, rect):
            QGraphicsWidget.setGeometry(self, rect)
            self.geometryChanged.emit()
    else:

        def setGeometry(self, rect):
            QGraphicsWidget.setGeometry(self, rect)
Пример #17
0
class NoParametersObject(QObject):
    changed = Signal()
    """
    Class handling parameters when none are needed.

    It is also useful as a template to create a new parameter class.

    :Parameters:
        params : struct
            Structure holding the parameters for this class
    """
    def __init__(self, params, parent=None):
        QObject.__init__(self, parent)
        pass

    def widget(self, parent):
        """
        :returns: The widget used to get the values or None.
        :returntype: QWidget|None
        """
        return None

    @staticmethod
    def load(params, settings):
        """
        Load the parameters and save them in the `params` argument.

        :Parameters:
            params : struct
                Structure in which to place the parameters.
            settings : `QSettings`
                Settings object where the settings are read. No need to create a group ...
        """
        pass

    @staticmethod
    def save(params, settings):
        """
        Save the parameters contained in the `params` argument.

        :Parameters:
            params : struct
                Structure in which to place the parameters.
            settings : `QSettings`
                Settings object where the settings are read. No need to create a group ...
        """
        pass
Пример #18
0
class ThreadArduino(QThread):
    update_new_value = Signal(int)

    def __init__(self,
                 parent=None,
                 device=None,
                 temp_alert=None,
                 sound_alert=False):
        super(ThreadArduino, self).__init__(parent)
        self.keep_running = True
        self.dq_60 = deque(maxlen=60)
        self.serial_connection = None
        self.device = str(device)
        self.baud = 9600
        self.temp_alert = temp_alert
        self.sound_alert = sound_alert

        self.sound_test = SoundEnabled()

    def run(self):
        mutex.lock()
        try:
            self.serial_connection = serial.Serial(self.device,
                                                   9600,
                                                   timeout=4)
            while self.keep_running:
                mutex.unlock()
                try:
                    temp_val = self.serial_connection.readline()
                    res_re = re.search(';[0-9]+.[0-9]+;', temp_val)
                    if res_re is not None:
                        val_int = int(float(temp_val.split(';')[1]))
                        self.dq_60.appendleft(val_int)
                        self.update_new_value.emit(val_int)
                        self.sound_test.check(self.sound_alert,
                                              self.temp_alert, val_int)
                        # if self.sound_alert:
                        #     if val_int > self.temp_alert:
                        #         print('\a')
                except IndexError:
                    print("Err int")
                self.sleep(2)

        except (serial.SerialException, AttributeError):
            print("ERR CON")
        print("DONE")
        mutex.unlock()
class BLACSWindow(QMainWindow):
    newWindow = Signal(int)

    def event(self, event):
        result = QMainWindow.event(self, event)
        if event.type() == QEvent.WinIdChange:
            self.newWindow.emit(self.effectiveWinId())
        return result

    def closeEvent(self, event):
        #print 'aaaaa'
        if self.blacs.exit_complete:
            event.accept()
            if self.blacs._relaunch:
                logger.info('relaunching BLACS after quit')
                relaunch_delay = '2'
                if '--delay' in sys.argv:
                    index = sys.argv.index('--delay') + 1
                    try:
                        int(sys.argv[index])
                        sys.argv[index] = relaunch_delay
                    except:
                        sys.argv.insert(index, relaunch_delay)
                else:
                    sys.argv.append('--delay')
                    sys.argv.append(relaunch_delay)
                subprocess.Popen([sys.executable] + sys.argv)
        else:
            event.ignore()
            logger.info('destroy called')
            if not self.blacs.exiting:
                self.blacs.exiting = True
                self.blacs.queue.manager_running = False
                self.blacs.settings.close()
                experiment_server.shutdown()
                for module_name, plugin in self.blacs.plugins.items():
                    try:
                        plugin.close()
                    except Exception as e:
                        logger.error(
                            'Could not close plugin %s. Error was: %s' %
                            (module_name, str(e)))

                inmain_later(self.blacs.on_save_exit)

            QTimer.singleShot(100, self.close)
Пример #20
0
class CheckedList(QListWidget):
    """
	@brief Erzeugt eine Liste, in welcher der Inhalt abgehakt werden kann.

	In dieser Liste kann der Nutzer sämtliche Einträge abhaken.
	"""

    itemStateChanged = Signal(str, object)

    def __init__(self, parent=None):
        super(CheckedList, self).__init__(parent)

        self.itemChanged.connect(self.emitItemStateChanged)

    def addCheckableItem(self, label, state, isBonus=False):
        """
		Hängt einen Eintrag an das Ende der Liste an.
		"""

        self.insertCheckableItem(self.count(), label, state, isBonus)

    def insertCheckableItem(self, index, label, state, isBonus=False):
        """
		Fügt einen Eintrag an der angegebenen Indexposition ein.
		"""

        item = QListWidgetItem()
        item.setText(label)
        item.setCheckState(state)
        if isBonus:
            item.setData(Qt.ForegroundRole, QColor(Config.COLOR_BONUS))
            item.setFlags(item.flags() & Qt.ItemIsUserCheckable)
        self.insertItem(index, item)

    def setCheckableItems(self, labels, state=Qt.Unchecked):
        """
		Setzt alle Einträge.
		
		Will man den Zustand eines einzelnen Eintrags verändern, sollte addCheckableItem() oder insertCheckableItem() verwendet werden. Nachträglich kann man den Zustand natürlich durch checkItem() manipulieren.
		"""

        for item in labels:
            self.addCheckableItem(item, state)

    def emitItemStateChanged(self, item):
        self.itemStateChanged.emit(item.text(), item.checkState())
Пример #21
0
class GroupItem(QLabel):
    """A group heading in a list of items."""
    def __init__(self, vault, name, parent=None):
        super(GroupItem, self).__init__(parent)
        self.vault = vault
        self.name = name
        self.displayName = name or 'No Group'
        self.opened = True
        self.addWidgets()
        self.setText(self.displayName)

    def addWidgets(self):
        opener = QLabel(self)
        self.pixmap_open = QPixmap(asset('png', 'triangle-open.png'))
        self.pixmap_closed = QPixmap(asset('png', 'triangle-closed.png'))
        opener.setPixmap(self.pixmap_open)
        opener.resize(opener.pixmap().size())
        self.opener = opener
        self.setIndent(opener.width() + 12)
        self.setMargin(2)

    openStateChanged = Signal(str, str, bool)

    @Slot(int)
    def setMatchCount(self, nmatches):
        if nmatches == -1:
            self.setText(self.displayName)
        else:
            self.setText('%s (%d)' % (self.displayName, nmatches))

    def resizeEvent(self, event):
        size = self.height()
        x = (size - self.opener.width()) // 2
        y = (size - self.opener.height()) // 2 + 1
        self.opener.move(x, y)

    def mousePressEvent(self, event):
        if not self.opener.geometry().contains(event.pos()):
            return
        if self.opened:
            self.opener.setPixmap(self.pixmap_closed)
            self.opened = False
        else:
            self.opener.setPixmap(self.pixmap_open)
            self.opened = True
        self.openStateChanged.emit(self.vault, self.name, self.opened)
Пример #22
0
class GraphicsScene(QGraphicsScene):

    selectionRectPointChanged = Signal(QPointF)

    def __init__(self, *args):
        QGraphicsScene.__init__(self, *args)
        self.selectionRect = None

    def mousePressEvent(self, event):
        QGraphicsScene.mousePressEvent(self, event)

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            screenPos = event.screenPos()
            buttonDown = event.buttonDownScreenPos(Qt.LeftButton)
            if (screenPos - buttonDown).manhattanLength() > 2.0:
                self.updateSelectionRect(event)
        QGraphicsScene.mouseMoveEvent(self, event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            if self.selectionRect:
                self.removeItem(self.selectionRect)
                self.selectionRect = None
        QGraphicsScene.mouseReleaseEvent(self, event)

    def updateSelectionRect(self, event):
        pos = event.scenePos()
        buttonDownPos = event.buttonDownScenePos(Qt.LeftButton)
        rect = QRectF(pos, buttonDownPos).normalized()
        rect = rect.intersected(self.sceneRect())
        if not self.selectionRect:
            self.selectionRect = QGraphicsRectItem()
            self.selectionRect.setBrush(QColor(10, 10, 10, 20))
            self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200)))
            self.addItem(self.selectionRect)
        self.selectionRect.setRect(rect)
        if event.modifiers() & Qt.ControlModifier or \
                event.modifiers() & Qt.ShiftModifier:
            path = self.selectionArea()
        else:
            path = QPainterPath()
        path.addRect(rect)
        self.setSelectionArea(path)
        self.selectionRectPointChanged.emit(pos)
Пример #23
0
class summary_data(QObject):
    summary_data_changed = Signal()

    def __init__(self):
        super(summary_data, self).__init__()
        self.data = pd.DataFrame()

    def update_data(self, df_calc_data, s_tresh):
        if (df_calc_data is not None) and (len(df_calc_data) > 0):
            self.data = pd.DataFrame()
            self.data['CAGR'] = pd.np.power(
                (df_calc_data.ix[:, -1] / df_calc_data.ix[:, 0]), 1. /
                (df_calc_data.shape[1] - 1)) - 1
            self.data['Valutazione'] = (self.data.CAGR >
                                        s_tresh).map(threshold_labels)
        else:
            self.data = pd.DataFrame()
        self.summary_data_changed.emit()
Пример #24
0
class ExceptHook(QObject):
    handledException = Signal(object)

    def __init__(self, parent=None, stream=None, canvas=None, **kwargs):
        QObject.__init__(self, parent, **kwargs)
        self._stream = stream
        self._canvas = canvas

    def __call__(self, exc_type, exc_value, tb):
        if self._stream:
            header = exc_type.__name__ + ' Exception'
            if QThread.currentThread() != QCoreApplication.instance().thread():
                header += " (in non-GUI thread)"
            text = traceback.format_exception(exc_type, exc_value, tb)
            text.insert(0, '{:-^79}\n'.format(' ' + header + ' '))
            text.append('-' * 79 + '\n')
            self._stream.writelines(text)

        self.handledException.emit(((exc_type, exc_value, tb), self._canvas))
Пример #25
0
class DerangementComboBox(QComboBox):
	"""
	@brief Eine Combobox für Geistesstörungen.

	Diese ComboBox zeigt milde und schwere Geistesstörungen in unterschiedlichen Farben an und bietet spezielle Signale.
	"""


	derangementChanged = Signal(str, bool, object)


	def __init__(self, parent=None):
		super(DerangementComboBox, self).__init__(parent)

		self.__severeDerangements = []

		self.currentIndexChanged[str].connect(self.emitDerangementChanged)


	def addItems(self, items, severe=False):
		"""
		Fügt der Box eine Liste von Geistesstörungen einer bestimmten Kategorie hinzu.
		"""

		if severe:
			for item in items:
				self.addItem(item)
				self.__severeDerangements.append(item)
				self.setItemData(self.count()-1, QColor(Config.COLOR_DERANGEMENTS_SEVERE), Qt.BackgroundRole)
		else:
			QComboBox.addItems(self, items)


	def emitDerangementChanged(self, text):
		"""
		Ändert sich der ausgewählte Text der combobox, wird dieses Signal gesendet, welches als Zusatzfunktion noch mitteilt, ob es sich bei der gewählten Geistesstörung um eine schwere handelt, oder nicht.
		"""

		severe = False
		if text in self.__severeDerangements:
			severe = True

		self.derangementChanged.emit(text, severe, self)
class ReportItemDelegate(QStyledItemDelegate):
    got_verdict = Signal(str)

    def __init__(self, parent=None, *args):
        QStyledItemDelegate.__init__(self, parent, *args)

    def createEditor(self, parent, option, index):
        if index.model().get_item(index).waiting_evaluation:
            return AskVerdict(parent, self)
        else:
            return QStyledItemDelegate.createEditor(self, parent, option,
                                                    index)

    def paint(self, painter, option, index):
        # if item selected, override default theme
        # Keeps verdict color for cells and use a bold font
        if option.state & QStyle.State_Selected:
            option.state &= ~ QStyle.State_Selected
            option.font.setBold(True)

        QStyledItemDelegate.paint(self, painter, option, index)

        item = index.model().get_item(index)
        if item and item.downloading:
            # Draw progress bar
            progressBarOption = QStyleOptionProgressBarV2()
            progressBarHeight = option.rect.height() / 4
            progressBarOption.rect = QRect(
                option.rect.x(),
                option.rect.y() +
                (option.rect.height() - progressBarHeight),
                option.rect.width(),
                progressBarHeight)
            progressBarOption.minimum = 0
            progressBarOption.maximum = 100
            progressBarOption.textAlignment = Qt.AlignCenter

            progressBarOption.progress = item.progress

            QApplication.style().drawControl(
                QStyle.CE_ProgressBar,
                progressBarOption,
                painter)
Пример #27
0
class FillNaNDialog(QDialog):
    
    accepted = Signal(list)
  
    def __init__(self,section,parent=None):
        super(FillNaNDialog,self).__init__(parent)
        self.section = section
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle(self.tr("Fill NaN's"))
        self.setModal(True)
        self.resize(366, 274)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.setSizePolicy(sizePolicy)
        
        self.gridLayout=QGridLayout()
        
        self.fillWithLabel=QLabel(self.tr("Fill With"))
        self.fillWithEdit=QLineEdit()
        self.methodLabel=QLabel(self.tr("Fill Method"))
        self.fillMethodCombo=QComboBox()
        self.fillMethodCombo.addItems(['None','backfill','bfill','pad','ffill'])
        
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        
        self.gridLayout.addWidget(self.fillWithLabel,0,0)
        self.gridLayout.addWidget(self.fillWithEdit,0,1)
        self.gridLayout.addWidget(self.methodLabel,1,0)
        self.gridLayout.addWidget(self.fillMethodCombo,1,1)
        self.gridLayout.addWidget(self.buttonBox,2,1)
        self.setLayout(self.gridLayout)
        
    def accept(self):
        selection = [self.fillMethodCombo.currentText(),self.fillWithEdit.text(),self.section]
        super(FillNaNDialog, self).accept()
        self.accepted.emit(selection)
Пример #28
0
class ReplaceEntryDialog(QDialog):

    accepted = Signal(list)
    
    def __init__(self,section,parent=None):
        super(ReplaceEntryDialog,self).__init__(parent)
        self.section = section
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle(self.tr('Replace Entry'))
        self.setModal(True)
        self.resize(366, 274)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.setSizePolicy(sizePolicy)
        
        self.gridLayout = QGridLayout()
        
        self.toReplaceLabel = QLabel(self.tr("Value to Replace"))
        self.toReplaceLineEdit = QLineEdit()
        self.replaceWithLabel = QLabel(self.tr("Replace With"))
        self.replaceWithLineEdit = QLineEdit()
        
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        
        self.gridLayout.addWidget(self.toReplaceLabel,0,0)
        self.gridLayout.addWidget(self.toReplaceLineEdit,0,1)
        self.gridLayout.addWidget(self.replaceWithLabel,1,0)
        self.gridLayout.addWidget(self.replaceWithLineEdit,1,1)
        self.gridLayout.addWidget(self.buttonBox,2,1)
        self.setLayout(self.gridLayout)
        
    def accept(self):
        selection = [self.toReplaceLineEdit.text(),self.replaceWithLineEdit.text(),self.section]
        super(ReplaceEntryDialog, self).accept()
        self.accepted.emit(selection)     
Пример #29
0
class calc_data(QObject):
    calc_data_changed = Signal()

    def __init__(self):
        super(calc_data, self).__init__()
        self.data = pd.DataFrame()

    def update_data(self, df_loaded_data, idxA, idxB):
        if (df_loaded_data is not None) and (len(df_loaded_data) > 0):
            tmp = pd.DataFrame({
                'A': df_loaded_data.ix[idxA],
                'B': df_loaded_data.ix[idxB]
            }).T
            self.data = pd.DataFrame.from_items([
                (calc_labels[0], tmp.ix['A'] / tmp.sum()),
                (calc_labels[1], tmp.ix['B'] / tmp.sum()),
                (calc_labels[2], tmp.ix['A'] / tmp.ix['B'])
            ]).T
        else:
            self.data = pd.DataFrame()
        self.calc_data_changed.emit()
Пример #30
0
class SliderLabel(QWidget):
    '''SliderLabel is a widget containing a QSlider and a QSpinBox (or QDoubleSpinBox if decimals are required)
    The QSlider and SpinBox are connected so that a change in one causes the other to change. 
    '''
    changeSignal=Signal(int)
    def __init__(self,decimals=0): #decimals specifies the resolution of the slider.  0 means only integers,  1 means the tens place, etc.
        QWidget.__init__(self)
        self.slider=QSlider(Qt.Horizontal)
        self.decimals=decimals
        if self.decimals<=0:
            self.label=QSpinBox()
        else:
            self.label=QDoubleSpinBox()
            self.label.setDecimals(self.decimals)
        self.layout=QHBoxLayout()
        self.layout.addWidget(self.slider)
        self.layout.addWidget(self.label)
        self.setLayout(self.layout)
        self.slider.valueChanged.connect(lambda val: self.updateLabel(val/10**self.decimals))
        self.label.valueChanged.connect(self.updateSlider)
        self.valueChanged=self.label.valueChanged
    @Slot(int, float)
    def updateSlider(self,value):
        self.slider.setValue(int(value*10**self.decimals))
    def updateLabel(self,value):
        self.label.setValue(value)
    def value(self):
        return self.label.value()
    def setRange(self,minn,maxx):
        self.slider.setRange(minn*10**self.decimals,maxx*10**self.decimals)
        self.label.setRange(minn,maxx)
    def setMinimum(self,minn):
        self.slider.setMinimum(minn*10**self.decimals)
        self.label.setMinimum(minn)
    def setMaximum(self,maxx):
        self.slider.setMaximum(maxx*10**self.decimals)
        self.label.setMaximum(maxx)
    def setValue(self,value):
        self.slider.setValue(value*10**self.decimals)
        self.label.setValue(value)