def save_image_to(self, path):

        TOP_MARGIN = 50
        LEFT_MARGIN = 50

        # Determine the size of the entire graph
        graph_size = self._graph_size()

        image_size = QSize(graph_size.width() + LEFT_MARGIN * 2,
                           graph_size.height() + TOP_MARGIN * 2
                           )

        image = QImage(image_size, QImage.Format_ARGB32)
        image.fill(Qt.white)  # white background

        painter = QPainter(image)
        painter.translate(TOP_MARGIN, LEFT_MARGIN)
        painter.setRenderHint(QPainter.TextAntialiasing)
        self._paint(painter,
                    QPoint(-TOP_MARGIN, -LEFT_MARGIN),
                    QPoint(image_size.width(), image_size.height())
                    )
        painter.end()

        image.save(path)
Beispiel #2
0
 def sizeHint(self):
     s = QSize()
     s.setHeight(super(ListWidget, self).sizeHint().height())
     # hint to max text length
     # width from scrollbar is too big? just use half of it.
     s.setWidth(self.sizeHintForColumn(0) + self.verticalScrollBar().width() / 2)
     return s
Beispiel #3
0
    def sizeHint(self, option, index):
        k = "{}x{}".format(index.row(), index.column())
        if "{}x{}".format(index.row(), index.column()) in self.last_bbox:
            s = self.last_bbox[k]
            # print "reusing ndx={}  {}x{}".format(k,s.width(),s.height())
            del self.last_bbox[k]
            return QSize(s.width(), s.height())

        s = self.get_displayed_data(index)
        if s == None:
            return QSize(-1, -1)

        fm = QFontMetrics(option.font)
        w = self.table.columnWidth(index.column())
        # if option.rect.width() > 0:
        #     w = option.rect.width()
        size = fm.boundingRect(0, 0, w, 30000,
                               Qt.AlignTop | Qt.AlignLeft | Qt.TextWordWrap, s,
                               0, [])

        # if s and len(s) > 50:
        #     print("[{}] w={} / s.w={} s.h={} txt:{}".format(self.i,w,size.width(),size.height(),s))

        # h = max( size.height(), self.last_bbox.height())
        # print "using ndx={}  {}x{}".format(k, size.width(),size.height())
        return QSize(size.width(), size.height())  # FIXME hardcoded value
Beispiel #4
0
 def __init__(self, spiderName, resumable=False, parent=None):
     super(SpiderToolButton, self).__init__(parent)
     self._drag_start = None
     button_play = QToolButton()
     button_play.setIcon(QIcon("play.png"))
     self.triggered.connect(
         button_play.triggered
     )  # clicking the outer button run the play functionality
     button_play.setIconSize(QSize(32, 32))
     button_resume = QToolButton()
     button_resume.setEnabled(resumable)
     button_resume.setIcon(QIcon("resume.png"))
     button_resume.setIconSize(QSize(32, 32))
     button_pause = QToolButton()
     button_pause.setIcon(QIcon("pause.png"))
     button_pause.setIconSize(QSize(32, 32))
     self.label_spidername = QLabel(spiderName)
     self.label_spidername.setStyleSheet(self.stylesheet_label_spidername)
     layout = QGridLayout()
     layout.addWidget(self.label_spidername, 0, 0)
     layout.addWidget(button_pause, 1, 1)
     layout.addWidget(button_resume, 1, 2)
     layout.addWidget(button_play, 1, 3)
     layout.setContentsMargins(10, 8, 10, 8)
     self.setLayout(layout)
    def buttonsOrientationChanged(self, index):
        self.mainLayout.setSizeConstraint(QLayout.SetNoConstraint);
        self.setMinimumSize(0, 0);

        orientation = Qt.Orientation(int(self.buttonsOrientationComboBox.itemData(index)))

        if orientation == self.buttonBox.orientation():
            return

        self.mainLayout.removeWidget(self.buttonBox);

        spacing = self.mainLayout.spacing()

        oldSizeHint = self.buttonBox.sizeHint() + QSize(spacing, spacing);
        self.buttonBox.setOrientation(orientation)
        newSizeHint = self.buttonBox.sizeHint() + QSize(spacing, spacing)

        if orientation == Qt.Horizontal:
            self.mainLayout.addWidget(self.buttonBox, 2, 0);
            self.resize(self.size() + QSize(-oldSizeHint.width(), newSizeHint.height()))
        else:
            self.mainLayout.addWidget(self.buttonBox, 0, 3, 2, 1);
            self.resize(self.size() + QSize(newSizeHint.width(), -oldSizeHint.height()))

        self.mainLayout.setSizeConstraint(QLayout.SetDefaultConstraint)
Beispiel #6
0
    def data(self, index, role):
        if not index.isValid() or len(self.infoDict) == 0:
            return None

        seq = hiero.ui.activeSequence()
        if not seq:
            return None

        item = self.infoDict[index.row()]["Item"]

        if role == Qt.DecorationRole:
            if index.column() == 0:
                try:
                    if isinstance(item, hiero.core.Tag):
                        imageView = seq.thumbnail(item.inTime())
                    elif isinstance(item, hiero.core.Annotation):
                        imageView = seq.thumbnail(item.timelineIn())
                    pixmap = QtGui.QPixmap.fromImage(
                        imageView.scaledToWidth(100))
                except:
                    # SHOULD RETURN A BLACK PIXMAP HERE...
                    icon = QtGui.QIcon("icons:VideoOnlyWarning.png")
                    pixmap = icon.pixmap(icon.actualSize(QSize(26, 26)))
                return pixmap

            elif index.column() == 1:
                icon = QtGui.QIcon(self.infoDict[index.row()]["Icon"])
                pixmap = icon.pixmap(icon.actualSize(QSize(26, 26)))
                return pixmap

        elif role == Qt.DisplayRole:
            label = self.infoDict[index.row()]["Name"]
            timecode = self.infoDict[index.row()]["TimecodeStart"]
            note = self.infoDict[index.row()]["Note"]
            duration = self.infoDict[index.row()]["Duration"]

            if index.column() == 2:
                return label
            elif index.column() == 3:
                return timecode
            elif index.column() == 4:
                return duration
            elif index.column() == 5:
                return note

        elif role == Qt.EditRole:
            # We will update the note column
            if index.column() == 5:
                return

        elif role == Qt.TextAlignmentRole:

            if index.column() == 5:
                return Qt.AlignVCenter

            return Qt.AlignLeft | Qt.AlignVCenter

        else:
            return
Beispiel #7
0
 def minimumSizeHint(self):
     count = len(self.letters)
     widthAll = self.fontMetrics().width(self.letters) * H_GAP_PC
     widthW = self.fontMetrics().width("WW")
     heightOne = self.fontMetrics().height()
     if self.orientation == Qt.Vertical:
         return QSize(widthW, (heightOne * count) + HANDLE_OFFSET)
     return QSize(widthAll + HANDLE_OFFSET, heightOne * V_GAP_PC)
Beispiel #8
0
    def adjustHeight(self):
        count = self.count()
        list_height = 0
        for i in range(0, count):
            item = self.item(i)
            list_height += self.itemWidget(item).height()

        margins = self.getContentsMargins()
        size = QSize(self.width(), list_height + margins[1] + margins[3])
        return size.height()
Beispiel #9
0
 def data(self, index, role=Qt.DisplayRole):
     if not index.isValid():
         return None
     item = self.itemFromIndex(index)
     if not item.loaded:
         item.load()
     if role == Qt.CheckStateRole and type(item) == SpellItem:
         return item.checkstate
     if role == Qt.UserRole:
         return item
     if role == Qt.SizeHintRole:
         size = QSize()
         size.setHeight(48)
         return size
     return super().data(index, role)
Beispiel #10
0
    def __init__(self, parent=None, statusBarService=None):
        """
        Creates a QProgressBar and adds it to the given status bar (for
        threads that can provide accurate progress information).

        Note: The status bar can either be a QStatusBar or the StatusBarService. In the default
        BioPARKIN use, it is the StatusBarService instance.

        @todo: A throbber is created and also added to the status bar (for
        threads that can only provide start/stop information).
        """
        #        super(ProgressBarService, self).__init__(parent)   # done in __new__

        if statusBarService is not None:
            self.statusBarService = statusBarService
            self.progressBar = QProgressBar(None)  # used for showing progress
            self.progressBarMutex = QMutex()
            self.progressBar.hide()
            self.statusBarService.addPermanentWidget(self.progressBar)
            self.progressRunning = False

            self.throbber = QLabel()
            self.throbberRunning = False
            self.throbberMutex = QMutex()
            self.statusBarService.addPermanentWidget(self.throbber)
            self.throbber.show()
            self.throbber.hide()

            throbberImage = QMovie(":/images/Spinning_wheel_throbber.gif",
                                   parent=self.throbber)
            throbberImage.setScaledSize(QSize(24, 24))
            throbberImage.setCacheMode(QMovie.CacheAll)
            throbberImage.start()
            self.throbber.setMovie(throbberImage)
            self.throbber.setFixedSize(24, 24)
Beispiel #11
0
    def __init__(self, file_to_open=None, parent=None):
        super(MainWindow, self).__init__(parent)

        GlobalInfo.main_window = self

        # initialization
        self.caption = "angr Management"
        self.setMinimumSize(QSize(400, 400))
        self.setDockNestingEnabled(True)

        self.workspace = None

        self._states_toolbar = None  # type: StatesToolbar
        self._analysis_toolbar = None  # type: AnalysisToolbar
        self._progressbar = None  # type: QProgressBar

        self._status = ""
        self._progress = None

        self._init_menus()
        self._init_toolbars()
        self._init_statusbar()
        self._init_workspace()

        # I'm ready to show off!
        self.show()

        self.status = "Ready."

        if file_to_open is not None:
            # load a binary
            self._open_loadbinary_dialog(file_to_open)
Beispiel #12
0
    def _setItem(self, title, subtitle, pic_path):
        item_widget = QListWidgetItem()
        item_widget.setSizeHint(QSize(90, 60))
        self.list_widget.addItem(item_widget)

        label = MyLable(title, subtitle, pic_path)
        self.list_widget.setItemWidget(item_widget, label)
Beispiel #13
0
    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)
Beispiel #14
0
 def show_calorie_calc(self, row_count=0):
     '''
     show calorie calculator
     :return:
     '''
     if row_count > 0:
         row_count += 1
     self.clear_table(None, None)
     self.stuff_table.clearContents()
     self.stuff_table.setColumnCount(3)
     self.stuff_table.setRowCount(row_count)
     self.stuff_table.setHorizontalHeaderLabels(['Amount', 'Unit', 'Name'])
     if row_count > 0:
         stuff_widget = QWidget()
         stuff_pixmap = QPixmap('icons/add.png')
         stuff_icon = QIcon()
         stuff_add_bt = QToolButton()
         stuff_icon.addPixmap(stuff_pixmap)
         stuff_add_bt.setIcon(stuff_icon)
         stuff_add_bt.setIconSize(QSize(8, 8))
         stuff_add_bt.clicked.connect(
             lambda: self.stuff_table.insertRow(row_count - 1))
         stuff_layout = QHBoxLayout()
         stuff_layout.addWidget(stuff_add_bt)
         stuff_widget.setLayout(stuff_layout)
         self.stuff_table.setCellWidget(row_count - 1, 2, stuff_widget)
Beispiel #15
0
 def sizeHint(self):
     """ Returns the widget size hint (based on the editor font size) """
     fm = QFontMetricsF(self.editor.codeEdit.font())
     self.size_hint = QSize(fm.height(), fm.height())
     if self.size_hint.width() > 16:
         self.size_hint.setWidth(16)
     return self.size_hint
Beispiel #16
0
    def capture(self,
                region=None,
                selector=None,
                format=QImage.Format_ARGB32_Premultiplied):
        """Returns snapshot as QImage.

        :param region: An optional tuple containing region as pixel
            coodinates.
        :param selector: A selector targeted the element to crop on.
        :param format: The output image format.
        """
        if region is None and selector is not None:
            region = self.region_for_selector(selector)
        if region:
            x1, y1, x2, y2 = region
            w, h = (x2 - x1), (y2 - y1)
            image = QImage(QSize(x2, y2), format)
            painter = QPainter(image)
            self.main_frame.render(painter)
            painter.end()
            image = image.copy(x1, y1, w, h)
        else:
            self.main_frame.setScrollBarPolicy(QtCore.Qt.Vertical,
                                               QtCore.Qt.ScrollBarAlwaysOff)
            self.main_frame.setScrollBarPolicy(QtCore.Qt.Horizontal,
                                               QtCore.Qt.ScrollBarAlwaysOff)
            self.page.setViewportSize(self.main_frame.contentsSize())
            image = QImage(self.page.viewportSize(), format)
            painter = QPainter(image)
            self.main_frame.render(painter)
            painter.end()
        return image
    def __create_filter_ui(self):
        """ Create filter widgets """
        filter_layout = QHBoxLayout()
        filter_layout.setSpacing(1)
        filter_layout.setContentsMargins(0, 0, 0, 0)

        self.filter_reset_btn = QPushButton()
        icon = QIcon(':/filtersOff.png')
        self.filter_reset_btn.setIcon(icon)
        self.filter_reset_btn.setIconSize(QSize(22, 22))
        self.filter_reset_btn.setFixedSize(24, 24)
        self.filter_reset_btn.setToolTip('Reset filter')
        self.filter_reset_btn.setFlat(True)
        self.filter_reset_btn.clicked.connect(
            partial(self.on_filter_set_text, ''))

        self.filter_line = QLineEdit()
        self.filter_line.setPlaceholderText('Enter filter string here')
        self.filter_line.textChanged.connect(self.on_filter_change_text)

        completer = QCompleter(self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setModel(QStringListModel([], self))
        self.filter_line.setCompleter(completer)

        filter_layout.addWidget(self.filter_reset_btn)
        filter_layout.addWidget(self.filter_line)

        return filter_layout
Beispiel #18
0
    def set_Abutton(self, icon, glo):
        def show_about(nself):
            if nself.Arabic is None:
                Amsg = "<center>All credit reserved to the author of FQM "
                Amsg += " version " + version
                Amsg += ", This work is a free, open-source project licensed "
                Amsg += " under Mozilla Public License version 2.0 . <br><br>"
                Amsg += " visit us for more infos and how-tos :<br> "
                Amsg += "<b><a href='https://fqms.github.io/'> "
                Amsg += "https://fqms.github.io/ </a> </b></center>"
                Amsgb = "About FQM"
            else:
                Amsg = u" <center> "
                Amsg += u" إدارة الحشود الحر النسخة " + version + u" "
                Amsg += u"حقوق نشر هذا البرنامج محفوظة و تخضع "
                Amsg += u" لرخصة البرامج الحرة و مفتوحة المصدر "
                Amsg += u" Mozilla Public License version 2.0 . "
                Amsg += u"<br><br> "
                Amsg += u"للمزيد من المعلومات و الشروحات , قم بزيارة :"
                Amsg += u"<br> <b><a href='https://fqms.github.io/'>"
                Amsg += u"https://fqms.github.io </a> </b></center>"
                Amsgb = u"عن النظام"
            return QMessageBox.about(self, Amsgb, Amsg)

        self.abutton = QPushButton('', self)
        self.abutton.setIcon(QPixmap(icon))
        self.abutton.setIconSize(QSize(150, 70))
        self.abutton.setToolTip('About FQM')
        self.abutton.clicked.connect(partial(show_about, self))
        glo.addWidget(self.abutton)
Beispiel #19
0
    def __init__(self, presenter, parent=None):
        super(MainView, self).__init__(presenter, parent=parent)
        self.setLayout(QGridLayout())

        addEffects = QPushButton(self)
        addEffects.isWordWrap = False
        addEffects.setFlat(True)
        addEffects.setCursor(Qt.PointingHandCursor)
        addEffects.setStyleSheet("QPushButton{outline:0; border-radius: 0px}")
        addEffects.setIcon(QPixmap("gui\\Add-Effects.png"))
        addEffects.setIconSize(QSize(300, 50))

        self.layout().addWidget(addEffects, 0, 0, 1, 1)
        self.setMinimumSize(QSize(640, 480))

        addEffects.clicked.connect(self.addEffectsClicked)
Beispiel #20
0
    def set_viewport_size(self, width, height):
        """Sets the page viewport size.

        :param width: An integer that sets width pixel count.
        :param height: An integer that sets height pixel count.
        """
        self.page.setViewportSize(QSize(width, height))
Beispiel #21
0
 def setc1(self, path):
     self.c1scene.clear()
     self.c1 = Carrier(img=imread(path))
     size = len(self.c1.pixelData)
     if self.c1.img.ndim == 3:
         size *= 3
     size /= 8
     self.c1size = int(size)
     self.txtCarrierSize.setText(str(self.c1size))
     if self.c1.payloadExists():
         self.lblPayloadFound.setText(">>>>Payload Found<<<<")
         self.chkOverride.setEnabled(True)
     else:
         self.lblPayloadFound.setText("")
         self.chkOverride.setChecked(False)
         self.chkOverride.setEnabled(False)
     w, h = int(self.viewCarrier1.geometry().width()), int(
         self.viewCarrier1.geometry().height())
     pixMap = QPixmap(path)
     self.c1scene.addPixmap(
         pixMap.scaled(QSize(w, h), Qt.KeepAspectRatio,
                       Qt.SmoothTransformation))
     self.viewCarrier1.setScene(self.c1scene)
     self.viewCarrier1.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
     self.checkEmbed()
Beispiel #22
0
    def setLayout(self):
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)

        self.duckIcon = QIcon("duck.jpeg")
        self.happyDuckIcon = QIcon("happy-duck.jpeg")
        qWidget = QWidget()
        gridLayout = QGridLayout(qWidget)
        row = 0
        self.setCentralWidget(qWidget)

        row = row + 1
        self.rebootButton = QPushButton("Click to reset")
        #self.rebootButton.setIcon(QIcon("duck.jpeg"))
        self.rebootButton.setIconSize(QSize(200, 200))
        gridLayout.addWidget(self.rebootButton, row, 0)
        self.rebootButton.clicked.connect(self.reboot)

        if filecmp.cmp("wpa_supplicant.conf", "wpa_supplicant.conf.orig"):
            self.myStatusBar.showMessage("Waiting to onboard.")
            self.rebootButton.setIcon(self.duckIcon)
            self.thread = Timer(5, self.checkFiles)
            self.thread.start()
        else:
            self.rebootButton.setIcon(self.happyDuckIcon)
            self.myStatusBar.showMessage("waiting for DHCP address")
            interface = "wlan1"
            p = subprocess.Popen(["/sbin/dhclient", interface],
                                 shell=False,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            res, err = p.communicate()
Beispiel #23
0
 def getSizeHint(self, row, column, item):
     """
   Return the size hint for a cell
 """
     if column == 0:
         return QSize(200, 26)
     return None
Beispiel #24
0
 def sizeHint(self):
     """
   Specifies the default size hint for this widget
   @ In, None
   @ Out, size, QSize, suggested size
 """
     return QSize(200, 200)
Beispiel #25
0
    def set_data(self, base_time, employee_id):
        global dao

        # self.potential_tasks_cache = PotentialTasksCache(dao.task_dao,base_time.date())
        # self.time_edit_dialog.set_potential_tasks_cache(self.potential_tasks_cache)

        self.employee_id = employee_id

        self.employee = dao.employee_dao.find_by_id(employee_id)
        self.all_tars = dao.task_action_report_dao.load_task_action_reports_for_edit(
            self.employee, base_time.date())
        self.added_tars = []

        self.manual_work_timetracks = dao.timetrack_dao.all_work_for_employee_date_manual(
            self.employee.employee_id, base_time.date())
        self.manual_presence_timetracks = dao.timetrack_dao.all_manual_presence_timetracks(
            self.employee, base_time.date())
        self.presence_task_id = dao.task_action_report_dao.presence_task(
        ).task_id

        self.base_time = base_time

        self.tar_to_delete = []

        self.presence_dialog.set_base_date(base_time.date())
        self._redraw()

        box = self.view.scene().sceneRect().size().toSize()
        s = QSize(box.width(), box.height() + 80)
        self.view.setMinimumSize(s)
Beispiel #26
0
    def sizeHint(self, option, index):
        '''Custom size calculation of our items'''

        uid = to_str(index.data(role=IDROLE)) + 'x' + str(option.rect.width(
        ))  #Fix Bug #967 (sometime uid have some strange unicode chars ... ?)
        try:
            return self.memoized_size[uid]
        except:
            tweet = to_str(index.data(Qt.DisplayRole))

            # One time is enought sizeHint need to be fast

            if not self.fm:
                self.normFont = QFont(option.font)
                self.normFont.setPointSizeF(option.font.pointSizeF() *
                                            self.fsize)
                self.fm = QFontMetrics(self.normFont)

            if not self.minifm:
                self.miniFont = QFont(option.font)
                self.miniFont.setPointSizeF(option.font.pointSizeF() * 0.8 *
                                            self.fsize)
                self.minifm = QFontMetrics(self.miniFont)

            height = self.fm.boundingRect(
                0,
                0,
                option.rect.width() - 75,
                800,
                int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap),
                tweet,
            ).height()

            reply_text = to_str(index.data(role=REPLYTEXTROLE))
            if reply_text:
                height += self.minifm.boundingRect(
                    0,
                    0,
                    option.rect.width() - 75,
                    800,
                    int(Qt.AlignTop) | int(Qt.AlignLeft)
                    | int(Qt.TextWordWrap),
                    reply_text,
                ).height() + 5

            height += self.minifm.boundingRect(
                0,
                0,
                option.rect.width() - 75,
                800,
                int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap),
                'LpqAT',
            ).height()
            height += 10  # Spacer

            if height < 70:
                height = 70
            self.memoized_size[uid] = QSize(option.rect.width(), height)
            return self.memoized_size[uid]
Beispiel #27
0
 def read_settings(self):
     settings = get_settings()
     screen = QApplication.desktop().screenGeometry()
     h = min(screen.height() * 5 / 6., 900)
     size = QSize(min(screen.width() * 5 / 6., 1200), h)
     pos = settings.value("pos", None)
     savesize = settings.value("size", size)
     if savesize.width() > screen.width():
         savesize.setWidth(size.width())
     if savesize.height() > screen.height():
         savesize.setHeight(size.height())
     self.resize(savesize)
     if ((pos is None or pos.x() + savesize.width() > screen.width() or
          pos.y() + savesize.height() > screen.height())):
         self.move(screen.center() - self.rect().center())
     else:
         self.move(pos)
Beispiel #28
0
 def create_header_bar(self, layout):
     back_button = QToolButton()
     back_button.setIconSize(QSize(30, 30))
     back_button.setIcon(QIcon(os.path.join("icons", "ic_action_back.png")))
     back_button.setStyleSheet("border: 0px;")
     back_button.setToolTip("Zurück")
     back_button.clicked.connect(self.back)
     layout.addWidget(back_button)
Beispiel #29
0
 def create_header_bar(self, layout):
     self.sync_button = QToolButton()
     self.sync_button.setIconSize(QSize(30, 30))
     self.sync_button.setIcon(QIcon(os.path.join("icons", "ic_action_sync.png")))
     self.sync_button.setStyleSheet("border: 0px;")
     self.sync_button.setToolTip("Sync")
     self.sync_button.clicked.connect(self.sync_clicked)
     self.sync_button.setVisible(False)
     layout.addWidget(self.sync_button)
     self.clipboard_button = QToolButton()
     self.clipboard_button.setIconSize(QSize(30, 30))
     self.clipboard_button.setIcon(QIcon(os.path.join("icons", "ic_action_copy.png")))
     self.clipboard_button.setStyleSheet("border: 0px;")
     self.clipboard_button.setToolTip("in die Zwischenablage")
     self.clipboard_button.clicked.connect(self.copy_to_clipboard)
     self.clipboard_button.setVisible(False)
     layout.addWidget(self.clipboard_button)
Beispiel #30
0
 def forceRepaint(self):
     """
     TOWRITE
     """
     # HACK: Take that QMdiArea!
     hack = self.size()  # QSize
     self.resize(hack + QSize(1, 1))
     self.resize(hack)
Beispiel #31
0
    def __init__(self, movieObj, parent):
        super(MovieItem, self).__init__(parent)

        self.movieObj = movieObj

        self.setSizeHint(QSize(310, 500))

        self.setData(Qt.UserRole, movieObj)
Beispiel #32
0
    def paint(self, painter, point):
        painter.save()

        size = QSize(self.width(), self.height())
        painter.setBrush(self.bg_color)
        painter.drawRoundedRect(QRect(point, size), BLOCK_RADIUS, BLOCK_RADIUS)

        # Рисуем столбцы
        p = QPoint(point) + QPoint(0, BLOCK_RADIUS)
        for c in self.columns:
            p += QPoint(BLOCK_RADIUS, 0)
            c.paint(painter, p)
            p += QPoint(c.width(), 0)

        # Рисуем левые порты
        if len(self.left_pins):
            p = QPoint(point)
            p += QPoint(0, size.height() / (len(self.left_pins) + 1))
            for lp in self.left_pins:
                lp.paint(painter, p)
                p += QPoint(0, size.height() / (len(self.left_pins) + 1))

        # Рисуем правые порты
        if len(self.right_pins):
            p = QPoint(point)
            p += QPoint(size.width(),
                        size.height() / (len(self.right_pins) + 1))
            for rp in self.right_pins:
                rp.paint(painter, p)
                p += QPoint(0, size.height() / (len(self.right_pins) + 1))

        painter.restore()
Beispiel #33
0
 def _onStyleChanged(self):
     """ Updates stylesheet and brushes. """
     fm = QFontMetricsF(self.editor.codeEdit.font())
     self.size_hint = QSize(fm.height(), fm.height())
     style = self.currentStyle
     self.back_brush = QBrush(QColor(style.panelsBackgroundColor))
     self.active_line_brush = QBrush(QColor(style.activeLineColor))
     self.separator_pen = QPen(QColor(style.panelSeparatorColor))
     # qss = self.QSS % {"back": style.activeLineColor,
     #                   "color": style.tokenColor(Text)}
     # self.setStyleSheet(qss)
     self.updateGeometry()
Beispiel #34
0
    def paint(self, painter, point):
        painter.save()

        size = QSize(self.width(), self.height())
        painter.setBrush(self.bg_color)
        painter.drawRoundedRect(QRect(point, size), BLOCK_RADIUS, BLOCK_RADIUS)

        # Рисуем столбцы
        p = QPoint(point) + QPoint(0, BLOCK_RADIUS)
        for c in self.columns:
            p += QPoint(BLOCK_RADIUS, 0)
            c.paint(painter, p)
            p += QPoint(c.width(), 0)

        # Рисуем левые порты
        if len(self.left_pins):
            p = QPoint(point)
            p += QPoint(0, size.height() / (len(self.left_pins) + 1))
            for lp in self.left_pins:
                lp.paint(painter, p)
                p += QPoint(0, size.height() / (len(self.left_pins) + 1))

        # Рисуем правые порты
        if len(self.right_pins):
            p = QPoint(point)
            p += QPoint(size.width(), size.height() / (len(self.right_pins) + 1))
            for rp in self.right_pins:
                rp.paint(painter, p)
                p += QPoint(0, size.height() / (len(self.right_pins) + 1))

        painter.restore()
Beispiel #35
0
 def _onStyleChanged(self):
     """ Updates brushes and pens """
     style = self.currentStyle
     self.font = QFont(self.currentStyle.fontName, 7)
     self.font.setBold(True)
     fm = QFontMetricsF(self.editor.codeEdit.font())
     self.size_hint = QSize(16, 16)
     self.back_brush = QBrush(QColor(style.panelsBackgroundColor))
     self.active_line_brush = QBrush(QColor(style.activeLineColor))
     self.separator_pen = QPen(QColor(style.panelSeparatorColor))
     self.normal_pen = QPen(QColor(style.lineNbrColor))
     self.highlight_pen = QPen(QColor(style.tokenColor(Text)))
     self.repaint()
Beispiel #36
0
class MarkersPanel(Panel):
    """
    Panel used to draw a collection of marker.
    A marker is 16x16 icon placed at a specific line number.

    A marker is added/removed when the user click on the the widget or manually (using addMarker).

    Actually if there is no marker where the user clicked, the markerAddRequested signal is emitted as we don't known
    what kind of marker we must add.

    When a marker is removed by the user, the markerRemoved signal is emitted.

    .. note:: The markers position is updated whenever a line is added/removed.

    .. note:: The markers list is cleared when a new text is set on the text
              edit (see QCodeEdit.newTextSet signal)

    .. note:: If a marker goes out of documents (line number <= 0) the
              markerOutOfDoc is emitted.
    """

    #: Stylesheet
    # QSS = """QToolTip {
    #      background-color: %(back)s;
    #      color: %(color)s;
    #      border: 1px solid %(color)s;
    #      padding: 2px;
    #      opacity: 220;
    # }
    # """

    #: Signal emitted with the line number where the marker must be added
    addMarkerRequested = Signal(Panel, int)
    #: Signal emitted when a marker is removed by the user.
    markerRemoved = Signal(Panel, Marker)
    #: Signal emitted when a marker is out of the document. This usually
    #  happen when the user delete lines from the beginning of the doc.
    markerOutOfDoc = Signal(Panel, Marker)
    #: Signal emitted before clearing the markers when a new text is set to give
    #  a chance to the user to save the markers list.
    clearingMarkers = Signal(Panel)

    def __init__(self, name, markersReadOnly=False, parent=None):
        Panel.__init__(
            self, name, "Display markers foreach line", parent)
        self.markers = []
        #: prevent user from adding/removing markers with mouse click
        self.markersReadOnly = markersReadOnly
        self.setMouseTracking(True)
        self.timer = QTimer()
        self._tooltipPos = -1
        self._prev_line = -1
        self.logger = logging.getLogger(
            __name__ + "." + self.__class__.__name__)

    def addMarker(self, marker):
        """ Adds a marker to be displayed """
        self.markers.append(marker)
        self.update()

    def removeMarker(self, marker):
        """ Removes a marker """
        self.markers.remove(marker)
        self.update()

    def clearMarkers(self):
        """ Clears the markers list """
        self.clearingMarkers.emit(self)
        self.markers[:] = []
        self.update()

    def install(self, editor):
        Panel.install(self, editor)
        self.bc = self.editor.codeEdit.blockCount()
        self.__updateCursorPos()

    def _onStateChanged(self, state):
        Panel._onStateChanged(self, state)
        if state is True:
            self.editor.codeEdit.visibleBlocksChanged.connect(self.update)
            self.editor.codeEdit.blockCountChanged.connect(self.__onBlockCountChanged)
            self.editor.codeEdit.newTextSet.connect(self.__onNewTextSet)
            self.editor.codeEdit.keyPressed.connect(self.__updateCursorPos)
        else:
            self.editor.codeEdit.visibleBlocksChanged.disconnect(self.update)
            self.editor.codeEdit.blockCountChanged.disconnect(self.__onBlockCountChanged)
            self.editor.codeEdit.newTextSet.disconnect(self.__onNewTextSet)
            self.editor.codeEdit.keyPressed.disconnect(self.__updateCursorPos)

    def _onStyleChanged(self):
        """ Updates stylesheet and brushes. """
        fm = QFontMetricsF(self.editor.codeEdit.font())
        self.size_hint = QSize(fm.height(), fm.height())
        style = self.currentStyle
        self.back_brush = QBrush(QColor(style.panelsBackgroundColor))
        self.active_line_brush = QBrush(QColor(style.activeLineColor))
        self.separator_pen = QPen(QColor(style.panelSeparatorColor))
        # qss = self.QSS % {"back": style.activeLineColor,
        #                   "color": style.tokenColor(Text)}
        # self.setStyleSheet(qss)
        self.updateGeometry()

    def sizeHint(self):
        """ Returns the widget size hint (based on the editor font size) """
        fm = QFontMetricsF(self.editor.codeEdit.font())
        self.size_hint = QSize(fm.height(), fm.height())
        if self.size_hint.width() > 16:
            self.size_hint.setWidth(16)
        return self.size_hint

    def __onNewTextSet(self):
        """ Clears markers when a new text is set """
        self.clearMarkers()

    def __getMarkerForLine(self, l):
        """ Returns the marker for the line l if any, else return None """
        for m in self.markers:
            if m.position == l:
                return m
        return None

    def __updateCursorPos(self):
        """ Updates cursor pos variables """
        self.tcPos = self.editor.codeEdit.textCursor().blockNumber() + 1
        self.tcPosInBlock = self.editor.codeEdit.textCursor().positionInBlock()

    def __onBlockCountChanged(self, num):
        """ Handles lines added/removed events """
        # a l has beeen inserted or removed
        tcPos = self.editor.codeEdit.textCursor().blockNumber() + 1
        tcPosInBlock = self.editor.codeEdit.textCursor().positionInBlock()
        bc = self.bc
        if bc < num:
            self.onLinesAdded(num - bc, tcPos, tcPosInBlock)
        else:
            self.onLinesRemoved(bc - num, tcPos, tcPosInBlock)
        self.tcPosInBlock = self.tcPosInBlock
        self.bc = num

    def onLinesAdded(self, nbLines, tcPos, tcPosInBlock):
        """ Offsets markers positions with the number of line added """
        if self.tcPosInBlock > 0:
            self.tcPos += 1
            # offset each l after the tcPos by nbLines
        for marker in self.markers:
            if marker.position >= self.tcPos:
                marker.position += nbLines
        self.tcPos = tcPos
        self.tcPosInBlock = tcPosInBlock
        self.update()

    def onLinesRemoved(self, nbLines, tcPos, tcPosInBlock):
        """ Offsets markers positions with the number of line removed """
        for marker in self.markers:
            if marker.position >= self.tcPos:
                marker.position -= nbLines
                if marker.position < 1:
                    self.markerOutOfDoc.emit(self, marker)
        self.tcPos = tcPos
        self.tcPosInBlock = tcPosInBlock
        self.update()

    def paintEvent(self, event):
        """ Paints the widget """
        if self.enabled is False:
            return
        Panel.paintEvent(self, event)
        painter = QPainter(self)
        painter.fillRect(event.rect(), self.back_brush)
        for vb in self.editor.codeEdit.visible_blocks:
            l = vb.row
            marker = self.__getMarkerForLine(l)
            if marker:
                if marker.icon is not None:
                    r = QRect()
                    r.setX(vb.rect.x())
                    r.setY(vb.rect.y())
                    r.setWidth(self.size_hint.width())
                    r.setHeight(self.size_hint.height())
                    marker.icon.paint(painter, r)
        return

    def leaveEvent(self, event):
        """ Resets prev line to -1 when we leave otherwise the tooltip won't be
        shown next time we hover the marker """
        if self.enabled is False:
            return
        self._prev_line = -1

    def mouseMoveEvent(self, event):
        """ Shows a tooltip """
        if self.enabled is False:
            return
        pos = event.pos()
        y = pos.y()
        for vb in self.editor.codeEdit.visible_blocks:
            top = vb.top
            height = vb.height
            if top < y < top + height:
                marker = self.__getMarkerForLine(vb.row)
                if (marker is not None and
                        marker.tooltip is not None and
                        marker.tooltip != ""):
                    if self._prev_line != vb.row:
                        self.timer.stop()
                        self._tooltip = marker.tooltip
                        centerX = self.size_hint.width()
                        centerY = vb.rect.y()
                        self._tooltipPos = QPoint(centerX, centerY)
                        self._prev_line = vb.row
                        self.timer.singleShot(1500, self.displayTooltip)
                return

    def mouseReleaseEvent(self, event):
        """
        Adds/Remove markers on click
        """
        if self.enabled is False:
            return
        if self.markersReadOnly is True:
            return
        pos = event.pos()
        y = pos.y()
        for vb in self.editor.codeEdit.visible_blocks:
            top = vb.top
            height = vb.height
            if top < y < top + height:
                marker = self.__getMarkerForLine(vb.row)
                if marker is not None:
                    self.removeMarker(marker)
                    self.markerRemoved.emit(self, marker)
                    self.logger.debug("Marker removed")
                else:
                    self.logger.debug("Marker add requested (l: %d)" % vb.row)
                    self.addMarkerRequested.emit(self, vb.row)

    def displayTooltip(self):
        """ Display the tooltip """
        QToolTip.showText(self.mapToGlobal(self._tooltipPos),
                          self._tooltip,
                          self)
Beispiel #37
0
 def testQSizeToTuple(self):
     s = QSize(1, 2)
     self.assertEqual((1, 2), s.toTuple())
Beispiel #38
0
 def sizeHint(self):
     size = QSize()
     size.setHeight(QListWidget.sizeHint(self).height())
     size.setWidth(self.sizeHintForColumn(0))
     return size
Beispiel #39
0
class FoldPanel(Panel):
    """ This Panel display folding indicators and manage folding/unfolding a text


    The panel also handles line added/removed and update the indicators position automatically.

    .. note:: It does not parse the code to put fold indicators, this is the task of a code folder mode. Instead it
              provides an easy way for other modes to put fold indicators on the left margin.
    """
    #: Panel identifier
    IDENTIFIER = "Folding"
    DESCRIPTION = "Display code folding indicators"

    def __init__(self, parent=None):
        Panel.__init__(
            self, self.IDENTIFIER, self.DESCRIPTION, parent)
        self.fold_indicators = []
        self.setMouseTracking(True)
        self.logger = logging.getLogger(
            __name__ + "." + self.__class__.__name__)

    def addIndicator(self, start, end):
        """
        Adds a fold indicator
        :param start: Start line (1 based)
        :param end: End line
        """
        self.fold_indicators.append(FoldIndicator(start, end))
        self.update()

    def removeIndicator(self, indicator):
        """
        Remove a fold indicator
        :param indicator: Indicator to remove
        """
        self.fold_indicators.remove(indicator)
        self.update()

    def clearIndicators(self):
        """ Remove all indicators """
        self.fold_indicators[:] = []
        self.update()

    def install(self, editor):
        """ Install the Panel on the editor """
        Panel.install(self, editor)
        self.bc = self.editor.codeEdit.blockCount()
        self.__updateCursorPos()

    def _onStateChanged(self, state):
        Panel._onStateChanged(self, state)
        if state is True:
            self.editor.codeEdit.visibleBlocksChanged.connect(self.update)
            self.editor.codeEdit.blockCountChanged.connect(self.__onBlockCountChanged)
            self.editor.codeEdit.newTextSet.connect(self.__onNewTextSet)
            self.editor.codeEdit.keyPressed.connect(self.__updateCursorPos)
        else:
            self.editor.codeEdit.visibleBlocksChanged.disconnect(self.update)
            self.editor.codeEdit.blockCountChanged.disconnect(self.__onBlockCountChanged)
            self.editor.codeEdit.newTextSet.disconnect(self.__onNewTextSet)
            self.editor.codeEdit.keyPressed.disconnect(self.__updateCursorPos)

    def _onStyleChanged(self):
        """ Updates brushes and pens """
        style = self.currentStyle
        self.font = QFont(self.currentStyle.fontName, 7)
        self.font.setBold(True)
        fm = QFontMetricsF(self.editor.codeEdit.font())
        self.size_hint = QSize(16, 16)
        self.back_brush = QBrush(QColor(style.panelsBackgroundColor))
        self.active_line_brush = QBrush(QColor(style.activeLineColor))
        self.separator_pen = QPen(QColor(style.panelSeparatorColor))
        self.normal_pen = QPen(QColor(style.lineNbrColor))
        self.highlight_pen = QPen(QColor(style.tokenColor(Text)))
        self.repaint()

    def sizeHint(self):
        """ Returns a fixed size hint (16x16) """
        self.size_hint = QSize(16, 16)
        return self.size_hint

    def __onNewTextSet(self):
        self.clearIndicators()

    def getIndicatorForLine(self, line):
        """ Returns the fold indicator whose start position equals the line
        :param line: Line nbr of the start position of the indicator to get.
        :return: FoldIndicator or None
        """
        for m in self.fold_indicators:
            if m.start == line:
                return m
        return None

    def __updateCursorPos(self):
        """
        Update tcPos and tcPosInBlock
        :return:
        """
        self.tcPos = self.editor.codeEdit.textCursor().blockNumber() + 1
        self.tcPosInBlock = self.editor.codeEdit.textCursor().positionInBlock()

    def __onBlockCountChanged(self, num=-1):
        """ Handles line added/removed event """
        # a line has been inserted or removed
        tcPos = self.editor.codeEdit.textCursor().blockNumber() + 1
        tcPosInBlock = self.editor.codeEdit.textCursor().positionInBlock()
        bc = self.bc
        if bc < num:
            self.__onLinesAdded(num - bc, tcPos, tcPosInBlock)
        else:
            self.__onLinesRemoved(bc - num, tcPos, tcPosInBlock)
        self.tcPosInBlock = self.tcPosInBlock
        self.bc = num

    def __onLinesAdded(self, nbLines, tcPos, tcPosInBlock):
        """ Offsets markers positions with the number of line added """
        if self.tcPosInBlock > 0:
            self.tcPos += 1
        # offset each line after the tcPos by nbLines
        for marker in self.fold_indicators:
            if marker.start >= self.tcPos:
                marker.start += nbLines
            if marker.end >= self.tcPos:
                marker.end += nbLines
        self.tcPos = tcPos
        self.tcPosInBlock = tcPosInBlock
        self.update()

    def __onLinesRemoved(self, nbLines, tcPos, tcPosInBlock):
        """ Offsets markers positions with the number of line removed """
        for marker in self.fold_indicators:
            if marker.start >= self.tcPos:
                marker.start -= nbLines
                if marker.start < 1:
                    self.removeIndicator(marker)
            if marker.end >= self.tcPos:
                marker.end -= nbLines
            if marker.end == marker.start:
                self.removeIndicator(marker)
        self.tcPos = tcPos
        self.tcPosInBlock = tcPosInBlock
        self.update()

    def paintEvent(self, event):
        """ Paints the widget """
        if self.enabled is False:
            return
        Panel.paintEvent(self, event)
        painter = QPainter(self)
        painter.fillRect(event.rect(), self.back_brush)

        for vb in self.editor.codeEdit.visible_blocks:
            line = vb.row
            # paint marker for line
            marker = self.getIndicatorForLine(line)
            if marker is None:
                continue
                # use the normal pen to draw the fold indicator
            drawLines = False
            pen = self.normal_pen
            if marker.hover is True:
                pen = self.highlight_pen
                drawLines = True
            painter.setPen(pen)
            # get the text to draw
            txt = '-'
            if marker.folded is True:
                drawLines = False
                txt = '+'
            offset = 4
            h = self.size_hint.height()
            fm = QFontMetricsF(self.editor.codeEdit.font())
            hoffset = (fm.height() - h) / 2.0
            r = QRect(vb.rect.x(), vb.rect.y() + hoffset, self.size_hint.width(), self.size_hint.height())
            painter.setFont(self.font)
            painter.drawText(r, Qt.AlignVCenter | Qt.AlignHCenter, txt)
            w = self.size_hint.width() - 2 * offset
            h = self.size_hint.width() - 2 * offset
            hoffset = (fm.height() - h) / 2.0
            r.setX(vb.rect.x() + offset)
            r.setY(vb.rect.y() + hoffset)
            r.setWidth(w)
            r.setHeight(h)
            painter.drawRect(r)
            if drawLines is True:
                top = (vb.rect.x() + self.size_hint.width() / 2.0,
                       vb.rect.y() + hoffset + offset * 2)
                delta = ((marker.end - marker.start) * vb.height)  # - (vb.rect.height() / 2.0)
                bottom = (top[0], top[1] + delta)
                painter.drawLine(top[0], top[1], bottom[0], bottom[1])
                painter.drawLine(bottom[0], bottom[1], bottom[0] + self.size_hint.width() / 2.0, bottom[1])

        return

    def leaveEvent(self, event):
        """ Clears indicator hover states and repaint """
        for m in self.fold_indicators:
            m.hover = False
        self.repaint()

    def mouseMoveEvent(self, event):
        """ Detects indicator hover states """
        if self.enabled is False:
            return
        pos = event.pos()
        y = pos.y()
        repaint = False
        for m in self.fold_indicators:
            if m.hover is True:
                m.hover = False
                repaint = True
        for vb in self.editor.codeEdit.visible_blocks:
            top = vb.top
            height = vb.height
            if top < y < top + height:
                marker = self.getIndicatorForLine(vb.row)
                if marker is not None:
                    # mark it as hover and repaint
                    marker.hover = True
                    repaint = True
        if repaint is True:
            self.repaint()

    def mouseReleaseEvent(self, event):
        """
        Folds/Unfolds code blocks
        """
        if self.enabled is False:
            return
        pos = event.pos()
        y = pos.y()
        for vb in self.editor.codeEdit.visible_blocks:
            top = vb.top
            height = vb.height
            if top < y < top + height:
                marker = self.getIndicatorForLine(vb.row)
                if marker is not None:
                    marker.folded = not marker.folded
                    self.editor.codeEdit.fold(marker.start - 1, marker.end, marker.folded)
                    self.repaint()
Beispiel #40
0
 def sizeHint(self):
     """ Returns a fixed size hint (16x16) """
     self.size_hint = QSize(16, 16)
     return self.size_hint