예제 #1
1
파일: buffer.py 프로젝트: mut0u/emacs.d
    def __init__(self, url, color):
        QWidget.__init__(self)
        self.setStyleSheet("background-color: black")

        self.file_name_font = QFont()
        self.file_name_font.setPointSize(24)

        self.file_name_label = QLabel(self)
        self.file_name_label.setText(url)
        self.file_name_label.setFont(self.file_name_font)
        self.file_name_label.setAlignment(Qt.AlignCenter)
        self.file_name_label.setStyleSheet("color: #eee")

        self.qrcode_label = QLabel(self)

        self.notify_font = QFont()
        self.notify_font.setPointSize(12)
        self.notify_label = QLabel(self)
        self.notify_label.setText("Scan above QR to copy information")
        self.notify_label.setFont(self.notify_font)
        self.notify_label.setAlignment(Qt.AlignCenter)
        self.notify_label.setStyleSheet("color: #eee")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addStretch()
        layout.addWidget(self.qrcode_label, 0, Qt.AlignCenter)
        layout.addSpacing(20)
        layout.addWidget(self.file_name_label, 0, Qt.AlignCenter)
        layout.addSpacing(40)
        layout.addWidget(self.notify_label, 0, Qt.AlignCenter)
        layout.addStretch()

        self.qrcode_label.setPixmap(qrcode.make(url, image_factory=Image).pixmap())
예제 #2
0
    def show_modulation_info(self):
        show = not self.has_default_modulation or self.modulators[0] != Modulator("Modulation")

        if not show:
            self.ui.btnEditModulation.setStyleSheet("background: orange")
            font = QFont()
            font.setBold(True)
            self.ui.btnEditModulation.setFont(font)
        else:
            self.ui.btnEditModulation.setStyleSheet("")
            self.ui.btnEditModulation.setFont(QFont())

        cur_ind = self.ui.cBoxModulations.currentIndex()
        cur_mod = self.modulators[cur_ind]
        self.ui.lCarrierFreqValue.setText(cur_mod.carrier_frequency_str)
        self.ui.lCarrierPhaseValue.setText(cur_mod.carrier_phase_str)
        self.ui.lBitLenValue.setText(cur_mod.bit_len_str)
        self.ui.lSampleRateValue.setText(cur_mod.sample_rate_str)
        mod_type = cur_mod.modulation_type_str
        self.ui.lModTypeValue.setText(mod_type)
        if mod_type == "ASK":
            prefix = "Amplitude"
        elif mod_type == "PSK":
            prefix = "Phase"
        elif mod_type in ("FSK", "GFSK"):
            prefix = "Frequency"
        else:
            prefix = "Unknown Modulation Type (This should not happen...)"

        self.ui.lParamForZero.setText(prefix + " for 0:")
        self.ui.lParamForZeroValue.setText(cur_mod.param_for_zero_str)
        self.ui.lParamForOne.setText(prefix + " for 1:")
        self.ui.lParamForOneValue.setText(cur_mod.param_for_one_str)
예제 #3
0
    def __init__(self, parent=None, command="/bin/bash", font_size=14):
        super().__init__(parent)

        self._columns = 80
        self._rows = 24
        self._char_width = [0] * (self._columns + 1)
        self._char_height = [0] * (self._rows + 1)

        self.setFocusPolicy(Qt.StrongFocus)
        self.setAutoFillBackground(False)
        self.setAttribute(Qt.WA_OpaquePaintEvent, True)
        self.setCursor(Qt.IBeamCursor)
        font_name = "Monospace"

        if sys.platform == 'darwin':
            font_name = "Courier"

        font = QFont(font_name)
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(font_size)
        self.setFont(font)
        self._session = None
        self._last_update = 0
        self._screen = []
        self._text = []
        self._cursor_rect = None
        self._cursor_col = 0
        self._cursor_row = 0
        self._dirty = False
        self._blink = False
        self._press_pos = None
        self._selection = None
        self._clipboard = QApplication.clipboard()
        self._pixmap = None
예제 #4
0
 def __init__(self, printViewModel, baseFont):
     self.printViewModel = printViewModel # From core.gui.transaction_print
     self._rowFont = QFont(baseFont)
     self._splitFont = QFont(baseFont)
     self._splitFont.setPointSize(self._splitFont.pointSize()-2)
     self._headerFont = QFont(self._rowFont)
     self._headerFont.setBold(True)
예제 #5
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        source_model = self.sourceModel()
        if not source_index.isValid():
            return QVariant()
        source_data = source_model.data(source_index, role)
        if index.column() == source_model.columns_types.index('is_member') \
                and role == Qt.DisplayRole:
            value = {True: self.tr('yes'), False: self.tr('no'), None: self.tr('offline')}
            return value[source_data]

        if index.column() == source_model.columns_types.index('pubkey') \
            and role == Qt.DisplayRole:
            return source_data[:5]

        if role == Qt.TextAlignmentRole:
            if source_index.column() == source_model.columns_types.index('address') or source_index.column() == self.sourceModel().columns_types.index('current_block'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == source_model.columns_types.index('is_member'):
                return Qt.AlignCenter

        if role == Qt.FontRole:
            is_root_col = source_model.columns_types.index('is_root')
            index_root_col = source_model.index(source_index.row(), is_root_col)
            if source_model.data(index_root_col, Qt.DisplayRole):
                font = QFont()
                font.setBold(True)
                return font

        return source_data
예제 #6
0
    def convertParsedQFont(chars_sets, font):
        name = font['name']
        qfont = QFont( font['family'], int(font['pointsize']) )
        qfont.setBold( font['bold'] )

        # convert and return
        return NFontConverter.convertQFont( chars_sets, name, qfont )
예제 #7
0
    def draw_markings(self, painter):
        painter.save()
        painter.translate(self.width()/2, self.height()/2)
        scale = min((self.width() - self._margins)/120.0, (self.height() - self._margins)/120.0)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(12)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        painter.setPen(self.palette().color(QPalette.WindowText))

        i = 0
        while i < 360:
            if i % 45 == 0:
                painter.drawLine(0, -40, 0, -50)
                painter.drawText(-metrics.width(self._point_text[i])/2.0, -52, self._point_text[i])
            else:
                painter.drawLine(0, -45, 0, -50)

            painter.rotate(15)
            i += 15

        painter.restore()
예제 #8
0
 def __createTexts(self):
     """
     Private method to create the text items of the module item.
     """
     if self.model is None:
         return
     
     boldFont = QFont(self.font)
     boldFont.setBold(True)
     
     classes = self.model.getClasses()
     
     x = self.margin + self.rect().x()
     y = self.margin + self.rect().y()
     self.header = QGraphicsSimpleTextItem(self)
     self.header.setFont(boldFont)
     self.header.setText(self.model.getName())
     self.header.setPos(x, y)
     y += self.header.boundingRect().height() + self.margin
     if classes:
         txt = "\n".join(classes)
     else:
         txt = " "
     self.classes = QGraphicsSimpleTextItem(self)
     self.classes.setFont(self.font)
     self.classes.setText(txt)
     self.classes.setPos(x, y)
예제 #9
0
 def addGraphicsItems(self):
     self.mainRect = QGraphicsRectItem(QRectF(-15, -15, 30, 30), self)
     self.nodeTitle = QGraphicsTextItem(type(self).name, self)
     titleFont = QFont()
     titleFont.setBold(True)
     self.nodeTitle.setFont(titleFont)
     self.selectedChanged(self.isSelected())
예제 #10
0
 def __init__(self, bookmark, parent=None):
     """
     Constructor
     
     @param bookmark reference to the bookmark to be shown (Bookmark)
     @param parent reference to the parent widget (QWidget)
     """
     super(BookmarkInfoDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.__bookmark = bookmark
     
     self.icon.setPixmap(UI.PixmapCache.getPixmap("bookmark32.png"))
     
     font = QFont()
     font.setPointSize(font.pointSize() + 2)
     self.title.setFont(font)
     
     if bookmark is None:
         self.titleEdit.setEnabled(False)
     else:
         self.titleEdit.setText(bookmark.title)
         self.titleEdit.setFocus()
     
     msh = self.minimumSizeHint()
     self.resize(max(self.width(), msh.width()), msh.height())
예제 #11
0
 def _setupUi(self):
     self.setWindowTitle(tr("Schedule Modification Scope"))
     self.resize(333, 133)
     self.verticalLayout = QVBoxLayout(self)
     self.label = QLabel(tr("Do you want this change to affect all future occurrences of this schedule?"))
     font = QFont()
     font.setWeight(75)
     font.setBold(True)
     self.label.setFont(font)
     self.label.setWordWrap(True)
     self.verticalLayout.addWidget(self.label)
     self.label_2 = QLabel(tr(
         "You can force global scope (in other words, changing all future occurrences) by "
         "holding Shift when you perform the change."
     ))
     self.label_2.setWordWrap(True)
     self.verticalLayout.addWidget(self.label_2)
     self.horizontalLayout = QHBoxLayout()
     self.cancelButton = QPushButton(tr("Cancel"))
     self.cancelButton.setShortcut("Esc")
     self.horizontalLayout.addWidget(self.cancelButton)
     spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
     self.horizontalLayout.addItem(spacerItem)
     self.globalScopeButton = QPushButton(tr("All future occurrences"))
     self.globalScopeButton.setAutoDefault(False)
     self.horizontalLayout.addWidget(self.globalScopeButton)
     self.localScopeButton = QPushButton(tr("Just this one"))
     self.localScopeButton.setAutoDefault(False)
     self.localScopeButton.setDefault(True)
     self.horizontalLayout.addWidget(self.localScopeButton)
     self.verticalLayout.addLayout(self.horizontalLayout)
 def createLabel(self, text):
     lbl = QLabel(text)
     lbl.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     font = QFont()
     font.setPointSize(12)
     lbl.setFont(font)
     return lbl
예제 #13
0
    def __init__(self, text, parent):
        super(DragLabel, self).__init__(parent)

        metric = QFontMetrics(self.font())
        size = metric.size(Qt.TextSingleLine, text)

        image = QImage(size.width() + 12, size.height() + 12, QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(0, 0, 0, 0))

        font = QFont()
        font.setStyleStrategy(QFont.ForceOutline)

        painter = QPainter()
        painter.begin(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.drawRoundedRect(QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, Qt.RelativeSize)

        painter.setFont(font)
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter, text)
        painter.end()

        self.setPixmap(QPixmap.fromImage(image))
        self.labelText = text
예제 #14
0
파일: frontend.py 프로젝트: sbenchik/Codex
 def __init__(self, parent=None, command="/bin/bash",
              font_name="Monospace", font_size=18):
     super(TerminalWidget, self).__init__(parent)
     self.parent().setTabOrder(self, self)
     self.setFocusPolicy(Qt.WheelFocus)
     self.setAutoFillBackground(False)
     self.setAttribute(Qt.WA_OpaquePaintEvent, True)
     self.setCursor(Qt.IBeamCursor)
     font = QFont(font_name)
     font.setPixelSize(font_size)
     self.setFont(font)
     self._session = None
     self._last_update = None
     self._screen = []
     self._text = []
     self._cursor_rect = None
     self._cursor_col = 0
     self._cursor_row = 0
     self._dirty = False
     self._blink = False
     self._press_pos = None
     self._selection = None
     self._clipboard = QApplication.clipboard()
     QApplication.instance().lastWindowClosed.connect(Session.close_all)
     if command:
         self.execute()
예제 #15
0
 def __adjustItemFeatures(self, itm, rule):
     """
     Private method to adjust an item.
     
     @param itm item to be adjusted (QTreeWidgetItem)
     @param rule rule for the adjustment (AdBlockRule)
     """
     if not rule.isEnabled():
         font = QFont()
         font.setItalic(True)
         itm.setForeground(0, QColor(Qt.gray))
         
         if not rule.isComment() and not rule.isHeader():
             itm.setFlags(itm.flags() | Qt.ItemIsUserCheckable)
             itm.setCheckState(0, Qt.Unchecked)
             itm.setFont(0, font)
         
         return
     
     itm.setFlags(itm.flags() | Qt.ItemIsUserCheckable)
     itm.setCheckState(0, Qt.Checked)
     
     if rule.isCSSRule():
         itm.setForeground(0, QColor(Qt.darkBlue))
         itm.setFont(0, QFont())
     elif rule.isException():
         itm.setForeground(0, QColor(Qt.darkGreen))
         itm.setFont(0, QFont())
     else:
         itm.setForeground(0, QColor())
         itm.setFont(0, QFont())
예제 #16
0
 def refresh(self):
     """
     Public method to refresh the tree.
     """
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.__itemChangingBlock = True
     self.clear()
     
     boldFont = QFont()
     boldFont.setBold(True)
     
     self.__topItem = QTreeWidgetItem(self)
     self.__topItem.setText(0, self.__subscription.title())
     self.__topItem.setFont(0, boldFont)
     self.addTopLevelItem(self.__topItem)
     
     allRules = self.__subscription.allRules()
     
     index = 0
     for rule in allRules:
         item = QTreeWidgetItem(self.__topItem)
         item.setText(0, rule.filter())
         item.setData(0, Qt.UserRole, index)
         if self.__subscription.canEditRules():
             item.setFlags(item.flags() | Qt.ItemIsEditable)
         self.__adjustItemFeatures(item, rule)
         index += 1
     
     self.expandAll()
     self.showRule(None)
     self.__itemChangingBlock = False
     QApplication.restoreOverrideCursor()
     QApplication.processEvents()
예제 #17
0
    def paintEvent(self, event):
        # Check whether this orb is enhanced
        if type(self.parent) == Board:
            enh = self.parent.enhanced[self.position]
        else:
            enh = False

        painter = QPainter(self)
        painter.drawPixmap(event.rect().adjusted(2,2,-2,-2), self.pixmap())

        w = event.rect().width()

        if enh:
            path = QPainterPath()

            pen = QPen()
            pen.setWidth(1);
            pen.setBrush(Qt.white)

            brush = QBrush(Qt.yellow)

            font = QFont()
            font.setPointSize(20)
            font.setWeight(QFont.Black)
            
            path.addText(event.rect().x()+w-15,event.rect().y()+w-5,font,'+')

            painter.setPen(pen)
            painter.setBrush(brush)
            painter.setFont(font)

            painter.drawPath(path)
예제 #18
0
def pixmap(cursor, num_lines=6, scale=0.8):
    """Return a QPixmap displaying the selected lines of the document.

    If the cursor has no selection, num_lines are drawn.

    By default the text is drawn 0.8 * the normal font size. You can change
    that by supplying the scale parameter.

    """
    block = cursor.document().findBlock(cursor.selectionStart())
    c2 = QTextCursor(block)
    if cursor.hasSelection():
        c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor)
        c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
    else:
        c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor, num_lines)

    data = textformats.formatData('editor')
    doc = QTextDocument()
    font = QFont(data.font)
    font.setPointSizeF(font.pointSizeF() * scale)
    doc.setDefaultFont(font)
    doc.setPlainText(c2.selection().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlighter.highlight(doc, state=tokeniter.state(block))
    size = doc.size().toSize() + QSize(8, -4)
    pix = QPixmap(size)
    pix.fill(data.baseColors['background'])
    doc.drawContents(QPainter(pix))
    return pix
예제 #19
0
파일: Theme.py 프로젝트: Ultimaker/Uranium
    def __init__(self, engine, parent = None) -> None:
        super().__init__(parent)

        self._engine = engine
        self._styles = None  # type: Optional[QObject]
        self._path = ""
        self._icons = {}  # type: Dict[str, QUrl]
        self._images = {}  # type: Dict[str, QUrl]

        # Workaround for incorrect default font on Windows
        if sys.platform == "win32":
            default_font = QFont()
            default_font.setPointSize(9)
            QCoreApplication.instance().setFont(default_font)

        self._em_height = int(QFontMetrics(QCoreApplication.instance().font()).ascent())
        self._em_width = self._em_height

        # Cache the initial language in the preferences. For fonts, a special font can be defined with, for example,
        # "medium" and "medium_nl_NL". If the special one exists, getFont() will return that, otherwise the default
        # will be returned. We cache the initial language here is because Cura can only change its language if it gets
        # restarted, so we need to keep the fonts consistent in a single Cura run.
        self._preferences = UM.Application.Application.getInstance().getPreferences()
        self._lang_code = self._preferences.getValue("general/language")

        self._initializeDefaults()

        self.reload()
예제 #20
0
	def __init__(self, parent=None):
		super().__init__(parent)
		QPixmapCache.setCacheLimit(app_constants.THUMBNAIL_CACHE_SIZE[0]*
							 app_constants.THUMBNAIL_CACHE_SIZE[1])
		self._painted_indexes = {}

		#misc.FileIcon.refresh_default_icon()
		self.file_icons = misc.FileIcon()
		if app_constants.USE_EXTERNAL_VIEWER:
			self.external_icon = self.file_icons.get_external_file_icon()
		else:
			self.external_icon = self.file_icons.get_default_file_icon()

		self.font_size = app_constants.GALLERY_FONT[1]
		self.font_name =0 # app_constants.GALLERY_FONT[0]
		if not self.font_name:
			self.font_name = QWidget().font().family()
		self.title_font = QFont()
		self.title_font.setBold(True)
		self.title_font.setFamily(self.font_name)
		self.artist_font = QFont()
		self.artist_font.setFamily(self.font_name)
		if self.font_size is not 0:
			self.title_font.setPixelSize(self.font_size)
			self.artist_font.setPixelSize(self.font_size)
		self.title_font_m = QFontMetrics(self.title_font)
		self.artist_font_m = QFontMetrics(self.artist_font)
		t_h = self.title_font_m.height()
		a_h = self.artist_font_m.height()
		self.text_label_h = a_h + t_h * 2
		self.W = app_constants.THUMB_W_SIZE
		self.H = app_constants.THUMB_H_SIZE + app_constants.GRIDBOX_LBL_H#self.text_label_h #+ app_constants.GRIDBOX_LBL_H
예제 #21
0
    def initUi(self, options, enabledOptions, headerOptions, singleSelectionMode):
        boldFont = QFont()
        boldFont.setBold(True)

        # set the selection mode
        if not singleSelectionMode:
            self.listView_options.setSelectionMode(QAbstractItemView.ExtendedSelection)

        # create enableItems if none
        if enabledOptions is None:
            enabledOptions = [True for idx in range(len(options))]

        # Insert the choices
        self.standaredItemModel = QStandardItemModel(self.listView_options)
        self.standaredItemModel.itemChanged.connect(self.onItemChanged)
        for idx in range(len(options)):
            standaredItem = QStandardItem(options[idx])
            standaredItem.setSelectable(enabledOptions[idx])
            if idx in headerOptions:
                standaredItem.setFont(boldFont)
            self.standaredItemModel.appendRow(standaredItem)

        self.listView_options.setModel(self.standaredItemModel)

        # disable select all / de select all buttons if in single selection
        # mode
        if singleSelectionMode:
            self.pushButton_sellectAll.setDisabled(True)
            self.pushButton_deSellectAll.setDisabled(True)
예제 #22
0
class HelpLabel(QLabel):

    def __init__(self, text, help_text):
        QLabel.__init__(self, text)
        self.help_text = help_text
        self.app = QCoreApplication.instance()
        self.font = QFont()

    def mouseReleaseEvent(self, x):
        custom_message_box(icon=QMessageBox.Information,
                           parent=self,
                           title=_('Help'),
                           text=self.help_text)

    def enterEvent(self, event):
        self.font.setUnderline(True)
        self.setFont(self.font)
        self.app.setOverrideCursor(QCursor(Qt.PointingHandCursor))
        return QLabel.enterEvent(self, event)

    def leaveEvent(self, event):
        self.font.setUnderline(False)
        self.setFont(self.font)
        self.app.setOverrideCursor(QCursor(Qt.ArrowCursor))
        return QLabel.leaveEvent(self, event)
    def __init__(self):
        """The constructor initializes the class AboutDialog."""
        super().__init__()
        self.setAttribute(Qt.WA_DeleteOnClose)

        # initialize class constants
        self._BUTTON_MIN_WIDTH = 110
        self._OXYGEN_PATH_48 = os.path.join("resources", "icons", "oxygen", "48")

        # fonts and margins settings
        hlFont = QFont()
        hlFont.setBold(True)
        hlFont.setPointSize(14)

        # scientific logo
        logo = QLabel(pixmap=QPixmap(os.path.join(self._OXYGEN_PATH_48, "applications-science.png")))

        logoLayout = QVBoxLayout()
        logoLayout.addWidget(logo)
        logoLayout.addStretch()

        # begin the content
        # headline and description text
        self.headline = QLabel()
        self.headline.setFont(hlFont)
        self.description = QLabel(wordWrap=True)

        # the list with the open button
        self.listWidget = QListWidget()
        self.listWidget.setMinimumWidth(420)
        self.createArticles()

        self.openButton = QPushButton()
        self.openButton.clicked.connect(self.openAction)

        listLayout = QHBoxLayout()
        listLayout.addWidget(self.listWidget)
        listLayout.addWidget(self.openButton, alignment=Qt.AlignTop)

        # create a close button
        line = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.HLine)
        self.closeButton = QPushButton()
        self.closeButton.setFixedWidth(self._BUTTON_MIN_WIDTH)
        self.closeButton.clicked.connect(self.close)

        # content layout
        contentLayout = QVBoxLayout()
        contentLayout.addWidget(self.headline)
        contentLayout.addWidget(self.description)
        contentLayout.addLayout(listLayout)
        contentLayout.addWidget(line)
        contentLayout.addWidget(self.closeButton, alignment=Qt.AlignRight)

        # main layout
        layout = QHBoxLayout(self)
        layout.addLayout(logoLayout)
        layout.addLayout(contentLayout)

        # translate the graphical user interface
        self.retranslateUi()
예제 #24
0
    def generate_tree_model(self, data_dict):
        """Generate a tree model for specified dictionary

        :param data_dict: A dictionary
        :type data_dict: dict
        :return: list of QTreeWidgetItem
        :rtype list:
        """
        widget_items = []
        font = QFont()
        font.setBold(True)
        for key in data_dict.keys():
            entry = data_dict[key]
            key_item = QTreeWidgetItem()
            key_item.setText(0, str(key))
            key_item.setFont(0, font)
            if isinstance(entry, dict):
                items = self.generate_tree_model(entry)
                key_item.addChildren(items)
            else:
                # value_item = QTreeWidgetItem()
                key_item.setText(1, str(entry))
                key_item.setFlags(key_item.flags() | Qt.ItemIsEditable)
                # key_item.addChild(key_item)
            widget_items.append(key_item)

        return widget_items
예제 #25
0
    def update_item(self):
        self.setText(0, self.download_info["name"])
        if self.download_info["name"] == u"<old version of your channel>":
            itfont = QFont(self.font(0))
            itfont.setItalic(True)
            self.setFont(0, itfont)
        else:
            self.font(0).setItalic(False)
        self.setText(1, format_size(float(self.download_info["size"])))

        try:
            self.progress_slider.setValue(int(self.download_info["progress"] * 100))
        except RuntimeError:
            self._logger.error("The underlying GUI widget has already been removed.")

        if self.download_info["vod_mode"]:
            self.setText(3, "Streaming")
        else:
            self.setText(3, DLSTATUS_STRINGS[eval(self.download_info["status"])])
        self.setText(4, "%s (%s)" % (self.download_info["num_connected_seeds"], self.download_info["num_seeds"]))
        self.setText(5, "%s (%s)" % (self.download_info["num_connected_peers"], self.download_info["num_peers"]))
        self.setText(6, format_speed(self.download_info["speed_down"]))
        self.setText(7, format_speed(self.download_info["speed_up"]))
        self.setText(8, "%.3f" % float(self.download_info["ratio"]))
        self.setText(9, "yes" if self.download_info["anon_download"] else "no")
        self.setText(10, str(self.download_info["hops"]) if self.download_info["anon_download"] else "-")
        self.setText(12, datetime.fromtimestamp(int(self.download_info["time_added"])).strftime('%Y-%m-%d %H:%M'))

        eta_text = "-"
        if self.get_raw_download_status() == DLSTATUS_DOWNLOADING:
            eta_text = duration_to_string(self.download_info["eta"])
        self.setText(11, eta_text)
예제 #26
0
            def cb_read(result):
                self.log_file.release()
                self.log_file = None

                self.label_download.setVisible(False)
                self.progress_download.setVisible(False)

                if result.error != None:
                    self.log('Error: ' + html.escape(str(result.error)), bold=True)
                    return

                try:
                    self.content = result.data.decode('utf-8')
                except UnicodeDecodeError:
                    # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails
                    self.log('Error: Log file is not UTF-8 encoded', bold=True)
                    return

                self.button_save.setEnabled(True)

                if self.continuous:
                    content = self.content.lstrip()
                else:
                    content = self.content

                self.edit_content.setPlainText('')

                font = QFont('monospace')
                font.setStyleHint(QFont.TypeWriter)

                self.edit_content.setFont(font)
                self.edit_content.setPlainText(content)
예제 #27
0
def setThemeEditorDatas(editor, themeDatas, pixmap, screenRect):
    textRect = themeTextRect(themeDatas, screenRect)
    x, y, width, height = themeEditorGeometry(themeDatas, textRect)
    editor.setGeometry(x, y, width, height)

    # p = editor.palette()
    ##p.setBrush(QPalette.Base, QBrush(pixmap.copy(x, y, width, height)))
    # p.setBrush(QPalette.Base, QColor(Qt.transparent))
    # p.setColor(QPalette.Text, QColor(themeDatas["Text/Color"]))
    # p.setColor(QPalette.Highlight, QColor(themeDatas["Text/Color"]))
    # p.setColor(QPalette.HighlightedText, Qt.black if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else Qt.white)
    # editor.setPalette(p)

    editor.setAttribute(Qt.WA_NoSystemBackground, True)

    bf = getThemeBlockFormat(themeDatas)
    editor.setDefaultBlockFormat(bf)

    # b = editor.document().firstBlock()
    # cursor = editor.textCursor()
    # cursor.setBlockFormat(bf)
    # while b.isValid():
    # bf2 = b.blockFormat()
    # bf2.merge(bf)
    # cursor.setPosition(b.position())
    ##cursor.setPosition(b.position(), QTextCursor.KeepAnchor)
    # cursor.setBlockFormat(bf2)
    # b = b.next()

    editor.setTabStopWidth(themeDatas["Spacings/TabWidth"])
    editor.document().setIndentWidth(themeDatas["Spacings/TabWidth"])

    editor.highlighter.setMisspelledColor(QColor(themeDatas["Text/Misspelled"]))

    cf = QTextCharFormat()
    # f = QFont()
    # f.fromString(themeDatas["Text/Font"])
    # cf.setFont(f)
    editor.highlighter.setDefaultCharFormat(cf)
    f = QFont()
    f.fromString(themeDatas["Text/Font"])
    # editor.setFont(f)

    editor.setStyleSheet("""
        background: transparent;
        color: {foreground};
        font-family: {ff};
        font-size: {fs};
        selection-color: {sc};
        selection-background-color: {sbc};
        """.format(
            foreground=themeDatas["Text/Color"],
            ff=f.family(),
            fs="{}pt".format(str(f.pointSize())),
            sc="black" if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else "white",
            sbc=themeDatas["Text/Color"],
    )
    )

    editor._fromTheme = True
예제 #28
0
 def data(self, index: QModelIndex, role=Qt.DisplayRole):
     i, j = index.row(), index.column()
     if role == Qt.DisplayRole:
         try:
             lbl = self.message_type[i]
         except IndexError:
             return False
         if j == 0:
             return lbl.name
         elif j == 1:
             return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[0] + 1
         elif j == 2:
             return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[1]
         elif j == 3:
             return lbl.color_index
         elif j == 4:
             return lbl.apply_decoding
     elif role == Qt.TextAlignmentRole:
         return Qt.AlignCenter
     elif role == Qt.FontRole and j == 0:
         font = QFont()
         font.setItalic(self.message_type[i].field_type is None)
         return font
     else:
         return None
예제 #29
0
    def __init__(self, engine, parent = None):
        super().__init__(parent)

        self._engine = engine
        self._styles = None
        self._path = ""
        self._icons = {}
        self._images = {}

        # Workaround for incorrect default font on Windows
        if sys.platform == "win32":
            default_font = QFont()
            default_font.setPointSize(9)
            QCoreApplication.instance().setFont(default_font)

        self._em_height = int(QFontMetrics(QCoreApplication.instance().font()).ascent())
        self._em_width = self._em_height;

        self._initializeDefaults()

        Preferences.getInstance().addPreference("general/theme", Application.getInstance().getApplicationName())
        try:
            theme_path = Resources.getPath(Resources.Themes, Preferences.getInstance().getValue("general/theme"))
            self.load(theme_path)
        except FileNotFoundError:
            Logger.log("e", "Could not find theme file.")
예제 #30
0
    def setNameAndBrush(self, sigma, color=Qt.black):
        self.sigma = sigma
        self.setText(f'σ{self.column}'.translate(self.sub_trans))
        if self.sigma is not None:
            total_window = (1 + 2 * int(self.sigma * self.window_size + 0.5))
            self.setToolTip(f'sigma = {sigma:.1f} pixels, window diameter = {total_window:.1f}')
        font = QFont()
        font.setPointSize(10)
        # font.setBold(True)
        self.setFont(font)
        self.setForeground(color)

        pixmap = QPixmap(self.pixmapSize)
        pixmap.fill(Qt.transparent)
        painter = QPainter()
        painter.begin(pixmap)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setPen(color)
        brush = QBrush(color)
        painter.setBrush(brush)
        painter.drawEllipse(QRect(old_div(self.pixmapSize.width(), 2) - old_div(self.brushSize, 2),
                                  old_div(self.pixmapSize.height(), 2) - old_div(self.brushSize, 2),
                                  self.brushSize, self.brushSize))
        painter.end()
        self.setIcon(QIcon(pixmap))
        self.setTextAlignment(Qt.AlignVCenter)
예제 #31
0
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QFont,QIcon
from PyQt5 import QtWidgets
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
butonFont = QFont("Arial",12)
yaziFont= QFont("Arial",16)
from firebase import firebase
import time
import main
firebase = firebase.FirebaseApplication("https://pankotek-3306f.firebaseio.com/",None)


class Canli(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("CANLI VERİ")
        self.setGeometry(50,50,800,400)
        self.setWindowIcon(QIcon("icons2/live-news.png"))
        self.setStyleSheet("background-color:#ccffff")#backgroundu oluşturmak için pencere rengi için
        self.arayuz()

    def arayuz(self):


예제 #32
0
    def InitWindow(self):

        self.headingg = QtWidgets.QLabel('<B> POWER ALERT</B>', self)
        self.headingg.setGeometry(
            300, 0, 300, 50
        )  # settingGeometry(x-axis, y-axis, width of widget, height of widget)
        self.headingg.setFont(QFont('SansSerif', 15))
        QToolTip.setFont(QFont('SansSerif', 10))

        self.l_bat = QtWidgets.QLabel('<B> Set Low Power % </B>', self)
        self.l_bat.setFont(QFont('SansSerif', 9))
        self.l_bat.setGeometry(3, 80, 220, 50)
        self.l_bat.setToolTip(
            'Set the battery % for which you want to get <B> low battery notification. </B>'
        )

        self.h_bat = QtWidgets.QLabel('<B> Set High Power % </B>', self)
        self.h_bat.setFont(QFont('SansSerif', 9))
        self.h_bat.setGeometry(3, 120, 240, 50)
        self.h_bat.setToolTip(
            'Set the battery % for which you want to get <B> high battery notification.</B>'
        )

        self.l_set = QSlider(Qt.Horizontal, self)
        self.l_set.setGeometry(170, 100, 150, 20)
        self.l_set.setMinimum(1)
        self.l_set.setMaximum(100)
        self.l_set.setValue(20)
        self.l_set.setTickPosition(QSlider.TicksAbove)

        self.l_spin = QSpinBox(self)
        self.l_spin.setGeometry(335, 100, 50, 20)
        self.l_spin.setValue(20)
        self.l_set.valueChanged.connect(self.l_spin.setValue)
        self.l_spin.valueChanged.connect(self.l_set.setValue)

        self.h_set = QSlider(Qt.Horizontal, self)
        self.h_set.setGeometry(170, 140, 150, 20)
        self.h_set.setMinimum(10)
        self.h_set.setMaximum(100)
        self.h_set.setValue(95)
        self.h_set.setTickPosition(QSlider.TicksAbove)

        self.h_spin = QSpinBox(self)
        self.h_spin.setGeometry(335, 140, 50, 20)
        self.h_spin.setValue(95)
        self.h_set.valueChanged.connect(self.h_spin.setValue)
        self.h_spin.valueChanged.connect(self.h_set.setValue)

        self.tl_txt = QtWidgets.QLabel('<B> Time Left: </B>', self)
        self.tl_txt.setFont(QFont('SansSerif', 9))
        self.tl_txt.setGeometry(3, 160, 240, 50)

        self.ni_txt = QtWidgets.QLabel('<B> ALERT Interval: </B>', self)
        self.ni_txt.setFont(QFont('SansSerif', 9))
        self.ni_txt.setGeometry(3, 200, 240, 50)
        self.n_interval = QtWidgets.QLineEdit("10", self)
        # self.n_interval.setText("10")
        self.n_interval.setGeometry(180, 210, 40, 30)

        self.sec = QtWidgets.QLabel('(seconds)', self)
        self.sec.setFont(QFont('SansSerif', 9))
        self.sec.setGeometry(230, 210, 80, 30)

        self.runn = QPushButton("RUN", self)
        self.runn.setFont(QFont('SansSerif', 9, weight=QFont.Bold))
        self.runn.setGeometry(100, 260, 80, 50)
        self.runn.clicked.connect(self.notification)

        self.bat_display = QProgressBar(self)
        self.bat_display.setGeometry(230, 370, 400, 80)
        self.bat_display.setFont(QFont('SansSerif', 20, weight=QFont.Bold))

        self.created_by = QtWidgets.QLabel(
            '<B> Created by- Manvir Singh Channa</B>', self)
        self.created_by.setGeometry(620, 440, 300, 50)
        self.to_contact = QtWidgets.QLabel(
            '<B> Contact for feedback- [email protected]</B>', self)
        self.to_contact.setGeometry(500, 460, 570, 50)

        self.setWindowTitle('Power Alert')
        self.setWindowIcon(QIcon('Icon.png'))
        self.setGeometry(self.top, self.bottom, self.height, self.width)
        self.show()
예제 #33
0
class HygrometerPrivate(QObject):
    def __init__(self, q):
        QObject.__init__(self)
        self.mPointer = q

        self.mDigitFont = QFont()
        self.mDigitFont.setPointSizeF(18)

        self.mValueFont = QFont()
        self.mValueFont.setPointSizeF(22)

        self.mDigitOffset = 105.0

        self.mValueOffset = -100

    def draw_background(self, painter):
        self.initCoordinateSystem(painter)

        pen = QPen(QColor(0, 0, 0))
        pen.setWidth(4)
        painter.setPen(pen)

        back1 = QRadialGradient(QPointF(0.0, 0.0), 180.0,
                                QPointF(-35.0, 145.0))
        back1.setColorAt(0.0, QColor(250, 250, 250))
        back1.setColorAt(1.0, QColor(20, 20, 20))

        back2 = QRadialGradient(QPointF(0.0, 0.0), 225.0, QPointF(76.5, 135.0))
        back2.setColorAt(0.0, QColor(10, 10, 10))
        back2.setColorAt(1.0, QColor(250, 250, 250))

        painter.setBrush(QBrush(back1))
        painter.drawEllipse(-162, -162, 324, 324)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(back2))
        painter.drawEllipse(-152, -152, 304, 304)

        shield = QRadialGradient(QPointF(0, 0), 182, QPointF(-12.0, -15.0))
        shield.setColorAt(0.0, Qt.white)
        shield.setColorAt(0.5, QColor(240, 240, 240))
        shield.setColorAt(1.0, QColor(215, 215, 215))

        painter.setBrush(QBrush(shield))
        painter.setPen(pen)
        painter.drawEllipse(-142, -142, 284, 284)

        painter.setPen(Qt.NoPen)

        painter.setBrush(QColor(0, 200, 0))
        angle = int(
            (3840 * (self.mPointer.nominal() - self.mPointer.minimal())) /
            (self.mPointer.maximal() - self.mPointer.minimal()))
        painter.drawPie(QRect(-141, -141, 282, 282), -480, 3840 - angle % 5760)

        painter.setBrush(QBrush(Qt.red))
        angle = int(
            (3840 * (self.mPointer.critical() - self.mPointer.minimal())) /
            (self.mPointer.maximal() - self.mPointer.minimal()))
        painter.drawPie(QRect(-141, -141, 282, 282), -480, 3840 - angle % 5760)

        painter.setBrush(QBrush(shield))
        painter.drawEllipse(-129, -129, 258, 258)

        painter.rotate(60)

        painter.save()
        painter.setBrush(QBrush(Qt.black))
        line_length = 10
        scaleTriangle = [QPoint(-6, 141), QPoint(6, 141), QPoint(0, 129)]

        for i in range(33):
            painter.setPen(pen)
            if i % 4:
                painter.drawLine(0, 140, 0, 140 - line_length)
            else:
                painter.setPen(Qt.NoPen)
                painter.drawConvexPolygon(QPolygon(scaleTriangle))

            painter.rotate(7.5)
            pen.setWidth(3)

            if i % 2:
                line_length = 10
            else:
                line_length = 5

        painter.restore()

        painter.setPen(Qt.black)
        painter.rotate(-60.0)
        painter.setFont(self.mDigitFont)

        for i in range(9):
            v = self.mPointer.minimal() + i * (self.mPointer.maximal() -
                                               self.mPointer.minimal()) / 8.0
            if abs(v) < 0.000001:
                v = 0.0
            val = "{}".format(v)
            Size = painter.fontMetrics().size(Qt.TextSingleLine, val)
            painter.save()
            painter.translate(
                self.mDigitOffset * math.cos((5 + i) * math.pi / 6.0),
                self.mDigitOffset * math.sin((5 + i) * math.pi / 6.0))
            painter.drawText(QPointF(Size.width() / -2.0,
                                     Size.height() / 4.0), val)
            painter.restore()

    def draw_value(self, painter):
        self.initCoordinateSystem(painter)
        hand = [-4, 0, -1, 129, 1, 129, 4, 0, 8, -50, -8, -50]

        hand_path = QPainterPath()
        hand_path.moveTo(QPointF(hand[0], hand[1]))

        for i in range(2, 10, 2):
            hand_path.lineTo(hand[i], hand[i + 1])

        hand_path.cubicTo(8.1, -51.0, 5.0, -48.0, 0.0, -48.0)
        hand_path.cubicTo(-5.0, -48.0, -8.1, -51.0, -8.0, -50.0)

        painter.save()

        painter.rotate(60.0)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(Qt.black))
        painter.rotate(
            ((self.mPointer.value() - self.mPointer.minimal()) * 240.0) /
            (self.mPointer.maximal() - self.mPointer.minimal()))

        painter.drawPath(hand_path)

        painter.drawEllipse(-10, -10, 20, 20)

        painter.restore()

        if self.mPointer.value() >= self.mPointer.critical():
            painter.setPen(Qt.red)

        painter.setFont(self.mValueFont)
        st = "{} %".format(self.mPointer.value())
        Size = painter.fontMetrics().size(Qt.TextSingleLine, st)
        painter.drawText(QPointF(Size.width() / -2, -self.mValueOffset), st)
        painter.end()

    def initCoordinateSystem(self, painter):
        side = min(self.mPointer.width(), self.mPointer.height())
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.mPointer.width() / 2,
                          self.mPointer.height() / 2)
        painter.scale(side / 335.0, side / 335.0)
예제 #34
0
class PunctaPainter():
    NODE_CIRCLE_PEN = QPen(QBrush(Qt.black), 1, Qt.SolidLine)
    NODE_CIRCLE_BRUSH = QBrush(QColor.fromRgbF(1.0, 1.0, 1.0, 0.3))
    NODE_CIRCLE_SELECTED_BRUSH = QBrush(QColor.fromRgbF(0.0, 1.0, 1.0, 0.3))
    NODE_CIRCLE_SELECTED_WRONGZ_PEN = QPen(QBrush(Qt.black), 1, Qt.DashLine)
    NODE_CIRCLE_WRONGZ_PEN = QPen(QBrush(QColor.fromRgbF(0.7, 0.7, 0.0, 0.9)),
                                  2, Qt.DashLine)
    NODE_CIRCLE_WRONGZ_BRUSH = QBrush(QColor.fromRgbF(1.0, 1.0, 0.0, 0.5))

    ANNOTATION_PEN = QPen(QBrush(Qt.yellow), 1, Qt.SolidLine)
    ANNOTATION_FONT = QFont("Arial", 12, QFont.Bold)
    ANNOTATION_OFFSET = 10
    ANNOTATION_HEIGHT = 40
    ANNOTATION_MAX_WIDTH = 512

    def __init__(self, painter, windowIndex, uiState, zoomMapFunc,
                 zoomDistFunc):
        self.p = painter
        self.windowIndex = windowIndex
        self.uiState = uiState
        self.zAt = self.uiState.zAxisAt
        self.zoomMapFunc = zoomMapFunc
        self.zoomDistFunc = zoomDistFunc

    def updateWindowIndex(self, windowIndex):
        self.windowIndex = windowIndex

    def drawPuncta(self, punctaMap):
        if self.uiState.hideAll:
            return  # Hidden, no paint for you.

        selectedPuncta = self.uiState.currentPuncta()
        selectedID = None if selectedPuncta is None else selectedPuncta.id
        if self.windowIndex < len(self.uiState._parent.puncta):
            for point in self.uiState._parent.puncta[self.windowIndex]:
                self.drawPunctum(point, selectedID)

    def drawPunctum(self, point, selectedID):
        if point is None:
            return
        x, y, z = self.zoomedLocation(point.location)
        isCurrent = (point.id == selectedID)
        radiusPx = point.radius

        sameZ = round(z) == self.zAt
        nearZ = self.isNearZ(z)
        drawAll = (self.uiState.branchDisplayMode == 1)
        drawNear = not (self.uiState.branchDisplayMode == 2)

        # 0 = nearby, 1 = all, 2 = only on this Z plane
        draw = (sameZ or drawAll or (drawNear and nearZ))
        if draw:
            self.drawCircle(x, y, sameZ, radiusPx, isCurrent)
            self.maybeDrawText(x, y, point)

    def drawCircle(self, x, y, sameZ, radiusPx, isCurrent):
        assert radiusPx is not None
        radiusX, radiusY = self.zoomDistFunc(radiusPx, radiusPx)
        pen = self.NODE_CIRCLE_PEN
        brush = self.NODE_CIRCLE_BRUSH
        if isCurrent:
            brush = self.NODE_CIRCLE_SELECTED_BRUSH
            if not sameZ:
                pen = self.NODE_CIRCLE_SELECTED_WRONGZ_PEN
        elif not sameZ:
            pen = self.NODE_CIRCLE_WRONGZ_PEN
            brush = self.NODE_CIRCLE_WRONGZ_BRUSH
        self.p.setPen(pen)
        self.p.setBrush(brush)
        self.p.drawEllipse(QPointF(x, y), radiusX, radiusY)

    def zoomedLocation(self, xyz):
        x, y, z = xyz
        zoomedXY = self.zoomMapFunc(x, y)
        return (zoomedXY.x(), zoomedXY.y(), z)

    def maybeDrawText(self, x, y, point):
        if not self.uiState.showAnnotations and not self.uiState.showIDs:
            return

        text = ""
        if self.uiState.showIDs:
            text = point.id
        if self.uiState.showAnnotations:
            text = point.annotation
        if text == "":
            return

        self.p.setFont(self.ANNOTATION_FONT)
        self.p.setPen(self.ANNOTATION_PEN)
        radiusX, _ = self.zoomDistFunc(point.radius, 0)

        textRect = QRectF(x + radiusX + self.ANNOTATION_OFFSET,
                          y - self.ANNOTATION_HEIGHT / 2,
                          self.ANNOTATION_MAX_WIDTH, self.ANNOTATION_HEIGHT)
        self.p.drawText(textRect, Qt.AlignVCenter, text)

    # HACK - utilities
    def isNearZ(self, z):
        return abs(z - self.zAt) < 3
예제 #35
0
    def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant:
        assert index.isValid()
        col = index.column()
        tx_item = index.internalPointer()
        tx_hash = tx_item['txid']
        conf = tx_item['confirmations']
        islock = tx_item['islock']
        is_parent = ('group_label' in tx_item)
        if is_parent and tx_hash in self.expanded_groups:
            expanded = True
        else:
            expanded = False

        if not is_parent:
            tx_group_icon = None
        elif not expanded:
            tx_group_icon = self.tx_group_expand_icn
        else:
            tx_group_icon = self.tx_group_collapse_icn
        try:
            status, status_str = self.tx_status_cache[tx_hash]
        except KeyError:
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            status, status_str = self.parent.wallet.get_tx_status(
                tx_hash, tx_mined_info, islock)

        if role not in (Qt.DisplayRole, Qt.EditRole):
            if col == HistoryColumns.TX_GROUP and role == Qt.DecorationRole:
                if tx_group_icon:
                    return QVariant(tx_group_icon)
            if col == HistoryColumns.STATUS and role == Qt.DecorationRole:
                return QVariant(read_QIcon(TX_ICONS[status]))
            elif col == HistoryColumns.STATUS and role == Qt.ToolTipRole:
                if tx_item['height'] == TX_HEIGHT_LOCAL:
                    msg = _(
                        "This transaction is only available on your local machine.\n"
                        "The currently connected server does not know about it.\n"
                        "You can either broadcast it now, or simply remove it."
                    )
                    return QVariant(msg)
                c = str(conf) + _(' confirmation' + ('s' if conf != 1 else ''))
                if conf < 6 and islock:
                    res = 'InstantSend, %s' % c
                else:
                    res = c
                return QVariant(res)
            elif col not in [HistoryColumns.DESCRIPTION, HistoryColumns.DIP2
                             ] and role == Qt.TextAlignmentRole:
                return QVariant(int(Qt.AlignRight | Qt.AlignVCenter))
            elif col != HistoryColumns.DESCRIPTION and role == Qt.FontRole:
                monospace_font = QFont(MONOSPACE_FONT)
                return QVariant(monospace_font)
            #elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole \
            #        and self.parent.wallet.invoices.paid.get(tx_hash):
            #    return QVariant(read_QIcon("seal"))
            elif col == HistoryColumns.DIP2 and role == Qt.ForegroundRole:
                dip2_brush = QBrush(QColor("#1c75bc"))
                return QVariant(dip2_brush)
            elif (col in (HistoryColumns.DESCRIPTION, HistoryColumns.AMOUNT)
                  and role == Qt.ForegroundRole):
                if is_parent and not expanded:
                    value = tx_item['group_value'].value
                else:
                    value = tx_item['value'].value
                if value < 0:
                    red_brush = QBrush(QColor("#BC1E1E"))
                    return QVariant(red_brush)
            elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \
                    and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None:
                blue_brush = QBrush(QColor("#1E1EFF"))
                return QVariant(blue_brush)
            return QVariant()
        if col == HistoryColumns.STATUS:
            return QVariant(status_str)
        elif col == HistoryColumns.DIP2:
            if is_parent and not expanded:
                return QVariant(tx_item.get('group_tx_type', ''))
            else:
                return QVariant(tx_item.get('tx_type', ''))
        elif col == HistoryColumns.DESCRIPTION:
            if is_parent and not expanded:
                return QVariant(tx_item['group_label'])
            else:
                return QVariant(tx_item['label'])
        elif col == HistoryColumns.AMOUNT:
            if is_parent and not expanded:
                value = tx_item['group_value'].value
            else:
                value = tx_item['value'].value
            v_str = self.parent.format_amount(value,
                                              is_diff=True,
                                              whitespaces=True)
            return QVariant(v_str)
        elif col == HistoryColumns.BALANCE:
            if is_parent and not expanded:
                balance = tx_item['group_balance'].value
            else:
                balance = tx_item['balance'].value
            balance_str = self.parent.format_amount(balance, whitespaces=True)
            return QVariant(balance_str)
        elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item:
            if is_parent and not expanded:
                return
            value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value)
            return QVariant(value_str)
        elif col == HistoryColumns.FIAT_ACQ_PRICE and \
                tx_item['value'].value < 0 and 'acquisition_price' in tx_item:
            if is_parent and not expanded:
                return
            # fixme: should use is_mine
            acq = tx_item['acquisition_price'].value
            return QVariant(self.parent.fx.format_fiat(acq))
        elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item:
            if is_parent and not expanded:
                return
            cg = tx_item['capital_gain'].value
            return QVariant(self.parent.fx.format_fiat(cg))
        elif col == HistoryColumns.TXID:
            return QVariant(tx_hash)
        return QVariant()
예제 #36
0
 def draw_text(self, qp):
     qp.setFont(QFont('Consolas', 9))
     qp.drawText(510, 390, 'Class Name:')
예제 #37
0
 def __getSongNameWidth(self):
     """ 计算歌名的长度 """
     fontMetrics = QFontMetrics(QFont('Microsoft YaHei', 10))
     self.songNameWidth = sum([fontMetrics.width(i) for i in self.songName])
예제 #38
0
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)

        # Reset box
        qp.setPen(Qt.NoPen)
        qp.setBrush(self.brushes[1024])
        qp.drawRoundedRect(self.resetRect, 5, 5)
        qp.setPen(QColor(0xf9f6f2))
        qp.setFont(QFont("Tahoma", 25))
        qp.drawText(self.resetRect, "Reset",
                    QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))

        # Description
        qp.setPen(QColor(0x776e65))
        qp.setFont(QFont("Tahoma", 12))
        qp.drawText(self.descriptionRect,
                    "2048 auto player\nwith Parallel Terraced Scan applied",
                    QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))

        # Titles left (game)
        for i in range(4):
            for j in range(4):
                rect = QRectF(j * 100, 100 + i * 100, 100, 100)
                qp.setPen(Qt.NoPen)
                # qp.setBrush(QColor(255,80,0,160))
                qp.setBrush(self.brushes[self.player1.game1.chessboard[i, j]])
                qp.drawRect(rect)

                if self.player1.game1.chessboard[i, j] < 10:
                    qp.setPen(QColor(0x776e65))
                else:
                    qp.setPen(QColor(0xf9f6f2))
                if self.player1.game1.chessboard[i, j] > 999:
                    qp.setFont(QFont("Tahoma", 30))
                elif self.player1.game1.chessboard[i, j] > 99:
                    qp.setFont(QFont("Tahoma", 40))
                else:  # 1 or 2 digits
                    qp.setFont(QFont("Tahoma", 50))
                if self.player1.game1.chessboard[i, j] != 0:
                    qp.drawText(rect, str(self.player1.game1.chessboard[i, j]),
                                QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))

        # Titles right (perception space)
        borderRect = QRectF(400, 100, 400, 400)
        qp.setPen(QColor(0xffffff))  # the black border
        qp.setBrush(QColor(0xffffff))  # the white background
        qp.drawRect(borderRect)

        # Draw perception space
        for i in range(4):
            for j in range(4):
                rect = QRectF(400 + j * 100, 100 + i * 100, 100, 100)

                if self.player1.controller1.workspace1.perceptionSpace[i,
                                                                       j] != 0:
                    qp.setPen(QColor(0x000000))
                    qp.setBrush(QColor(128, 128, 128, 30))
                    qp.drawRect(rect)

                qp.setPen(QColor(0x000000))
                if self.player1.controller1.workspace1.perceptionSpace[
                        i, j] > 999:
                    qp.setFont(QFont("Tahoma", 30))
                elif self.player1.controller1.workspace1.perceptionSpace[
                        i, j] > 99:
                    qp.setFont(QFont("Tahoma", 40))
                elif self.player1.controller1.workspace1.perceptionSpace[
                        i, j] > 9:
                    qp.setFont(QFont("Tahoma", 50))

        # Draw newly added structure
        # Draw titles
        if self.infoFromSignal != [] and type(
                self.infoFromSignal[0][1]) == int:
            cordinate = self.infoFromSignal[0]
            structureRect = QRectF(400 + cordinate[1] * 100,
                                   100 + cordinate[0] * 100, 100, 100)
            qp.setFont(self.len2Font(str(self.infoFromSignal[1])))
            qp.setPen(QColor(0x999999))
            text = str(self.infoFromSignal[1])
            #print("This is the TEXT!  "+text)
            qp.drawText(structureRect, text,
                        QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))
        # TODO: Draw relation

        # Draw concepts
        for i in range(len(self.conceptFromSignal)):
            #print('Drawing Concepts')
            conceptRect = QRectF(801, 100 + 20 * i, 120, 20)
            qp.setPen(QColor(0x999999))
            qp.setBrush(QColor(0xffffff))
            qp.drawRect(conceptRect)
            conceptActivityRect = QRectF(801, 100 + 20 * i,
                                         self.conceptFromSignal[i][1] * 10, 20)
            qp.setPen(Qt.NoPen)
            qp.setBrush(QColor(0xf2b179))
            qp.drawRect(conceptActivityRect)
            qp.setPen(QColor(0x000000))
            qp.setFont(QFont("Tahoma", 15))
            qp.drawText(conceptRect, str(self.conceptFromSignal[i][0]),
                        QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))

        # Draw coderack stat
        if len(self.codeRackStatFromSignal) > 0:
            statRect = QRectF(401, 15, 400, 40)
            qp.setPen(QColor(0x555555))
            qp.setFont(QFont("Tahoma", 20))
            statText = ''
            if len(self.codeRackStatFromSignal[1]) > 0:
                for i in self.codeRackStatFromSignal[1]:
                    statText += str(i) + ': ' + str(
                        self.codeRackStatFromSignal[0][i]) + '  '
                    qp.drawText(statRect, statText)

        # Draw proposal activities
        upRect = QRectF(800, 15, 20, 20)
        downRect = QRectF(800, 35, 20, 20)
        leftRect = QRectF(780, 35, 20, 20)
        rightRect = QRectF(820, 35, 20, 20)
        dirRect = {0: upRect, 1: downRect, 2: leftRect, 3: rightRect}
        if len(self.proposalsActivityFromSignal) > 0:
            for proposal in range(4):
                qp.setBrush(QColor(0xffffff))
                qp.drawRect(dirRect[proposal])
                if proposal in self.proposalsActivityFromSignal:
                    qp.setPen(QColor(0x000000))
                    qp.drawText(
                        dirRect[proposal],
                        str(self.proposalsActivityFromSignal[proposal]),
                        QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))

        # Draw stuctures
        strcTypeColor = {'same': Qt.gray, 'next': Qt.yellow}
        if len(self.structureDepictList) > 0:
            for strc in self.structureDepictList:
                pen = QPen(strcTypeColor[strc[4]], 2, Qt.SolidLine)
                qp.setPen(pen)
                qp.drawLine(strc[0], strc[1], strc[2], strc[3])

        qp.end()
예제 #39
0
    def FillSpecies(self):
        location = self.lblLocation.text()
        tempFilter = code_Filter.Filter()
        tempFilter.setLocationType("Location")
        tempFilter.setLocationName(location)

        # get species data from db
        thisWindowList = self.mdiParent.db.GetSpeciesWithData(tempFilter)

        # set up tblSpecies column headers and widths
        self.tblSpecies.setColumnCount(6)
        self.tblSpecies.setRowCount(len(thisWindowList) + 1)
        self.tblSpecies.horizontalHeader().setVisible(True)
        self.tblSpecies.setHorizontalHeaderLabels(
            ['Tax', 'Species', 'First', 'Last', 'Chlists', '% of Chlists'])
        header = self.tblSpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblSpecies.setShowGrid(False)

        font = QFont()
        font.setBold(True)
        count = 0
        nonSpeciesTaxaCount = 0

        # add species and dates to table row by row
        R = 0
        for species in thisWindowList:
            taxItem = QTableWidgetItem()
            taxItem.setData(Qt.DisplayRole, R)
            speciesItem = QTableWidgetItem()
            speciesItem.setText(species[0])
            firstItem = QTableWidgetItem()
            firstItem.setData(Qt.DisplayRole, species[1])
            lastItem = QTableWidgetItem()
            lastItem.setData(Qt.DisplayRole, species[2])
            checklistsItem = QTableWidgetItem()
            checklistsItem.setData(Qt.DisplayRole, species[5])
            percentageItem = QTableWidgetItem()
            percentageItem.setData(Qt.DisplayRole, species[6])

            self.tblSpecies.setItem(R, 0, taxItem)
            self.tblSpecies.setItem(R, 1, speciesItem)
            self.tblSpecies.setItem(R, 2, firstItem)
            self.tblSpecies.setItem(R, 3, lastItem)
            self.tblSpecies.setItem(R, 4, checklistsItem)
            self.tblSpecies.setItem(R, 5, percentageItem)

            self.tblSpecies.item(R, 1).setFont(font)

            # set the species to gray if it's not a true species
            if " x " in species[0] or "sp." in species[0] or "/" in species[0]:
                self.tblSpecies.item(R, 1).setForeground(Qt.gray)
                nonSpeciesTaxaCount += 1
            else:
                self.tblSpecies.item(R, 1).setForeground(
                    code_Stylesheet.speciesColor)
                count += 1

            R += 1

        labelText = "Species: " + str(count)
        if nonSpeciesTaxaCount > 0:
            labelText = labelText + " + " + str(nonSpeciesTaxaCount) + " taxa"

        self.lblSpecies.setText(labelText)
예제 #40
0
class BlenderLauncher(QMainWindow, BaseWindow, Ui_MainWindow):
    show_signal = pyqtSignal()
    close_signal = pyqtSignal()

    def __init__(self, app):
        super().__init__()
        self.setupUi(self)

        # Server
        self.server = QLocalServer()
        self.server.listen("blender-launcher-server")
        self.server.newConnection.connect(self.new_connection)

        # Global scope
        self.app = app
        self.favorite = None
        self.status = "None"
        self.app_state = AppState.IDLE
        self.cashed_builds = []
        self.notification_pool = []
        self.windows = [self]
        self.manager = PoolManager(200)
        self.timer = None

        # Setup window
        self.setWindowTitle("Blender Launcher")
        self.app.setWindowIcon(
            QIcon(taskbar_icon_paths[get_taskbar_icon_color()]))

        # Setup font
        QFontDatabase.addApplicationFont(
            ":/resources/fonts/OpenSans-SemiBold.ttf")
        self.font = QFont("Open Sans SemiBold", 10)
        self.font.setHintingPreference(QFont.PreferNoHinting)
        self.app.setFont(self.font)

        # Setup style
        file = QFile(":/resources/styles/global.qss")
        file.open(QFile.ReadOnly | QFile.Text)
        self.style_sheet = QTextStream(file).readAll()
        self.app.setStyleSheet(self.style_sheet)

        # Check library folder
        if is_library_folder_valid() is False:
            self.dlg = DialogWindow(
                self,
                title="Information",
                text="First, choose where Blender\nbuilds will be stored",
                accept_text="Continue",
                cancel_text=None,
                icon=DialogIcon.INFO)
            self.dlg.accepted.connect(self.set_library_folder)
        else:
            self.draw()

    def set_library_folder(self):
        library_folder = Path.cwd().as_posix()
        new_library_folder = QFileDialog.getExistingDirectory(
            self,
            "Select Library Folder",
            library_folder,
            options=QFileDialog.DontUseNativeDialog | QFileDialog.ShowDirsOnly)

        if new_library_folder:
            set_library_folder(new_library_folder)
            self.draw()

    def draw(self):
        self.HeaderLayout = QHBoxLayout()
        self.HeaderLayout.setContentsMargins(1, 1, 1, 0)
        self.HeaderLayout.setSpacing(0)
        self.CentralLayout.addLayout(self.HeaderLayout)

        self.SettingsButton = \
            QPushButton(QIcon(":resources/icons/settings.svg"), "")
        self.SettingsButton.setIconSize(QSize(20, 20))
        self.SettingsButton.setFixedSize(36, 32)
        self.WikiButton = \
            QPushButton(QIcon(":resources/icons/wiki.svg"), "")
        self.WikiButton.setIconSize(QSize(20, 20))
        self.WikiButton.setFixedSize(36, 32)
        self.MinimizeButton = \
            QPushButton(QIcon(":resources/icons/minimize.svg"), "")
        self.MinimizeButton.setIconSize(QSize(20, 20))
        self.MinimizeButton.setFixedSize(36, 32)
        self.CloseButton = \
            QPushButton(QIcon(":resources/icons/close.svg"), "")
        self.CloseButton.setIconSize(QSize(20, 20))
        self.CloseButton.setFixedSize(36, 32)
        self.HeaderLabel = QLabel("Blender Launcher")
        self.HeaderLabel.setAlignment(Qt.AlignCenter)

        self.HeaderLayout.addWidget(self.SettingsButton, 0, Qt.AlignLeft)
        self.HeaderLayout.addWidget(self.WikiButton, 0, Qt.AlignLeft)
        self.HeaderLayout.addWidget(self.HeaderLabel, 1)
        self.HeaderLayout.addWidget(self.MinimizeButton, 0, Qt.AlignRight)
        self.HeaderLayout.addWidget(self.CloseButton, 0, Qt.AlignRight)

        self.SettingsButton.setProperty("HeaderButton", True)
        self.WikiButton.setProperty("HeaderButton", True)
        self.MinimizeButton.setProperty("HeaderButton", True)
        self.CloseButton.setProperty("HeaderButton", True)
        self.CloseButton.setProperty("CloseButton", True)

        # Tab layout
        self.TabWidget = QTabWidget()
        self.CentralLayout.addWidget(self.TabWidget)

        self.LibraryTab = QWidget()
        self.LibraryTabLayout = QVBoxLayout()
        self.LibraryTabLayout.setContentsMargins(0, 0, 0, 0)
        self.LibraryTab.setLayout(self.LibraryTabLayout)
        self.TabWidget.addTab(self.LibraryTab, "Library")

        self.DownloadsTab = QWidget()
        self.DownloadsTabLayout = QVBoxLayout()
        self.DownloadsTabLayout.setContentsMargins(0, 0, 0, 0)
        self.DownloadsTab.setLayout(self.DownloadsTabLayout)
        self.TabWidget.addTab(self.DownloadsTab, "Downloads")

        self.LibraryToolBox = BaseToolBoxWidget(self)

        self.LibraryStableListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Stable Releases", "Nothing to show yet")
        self.LibraryDailyListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Daily Builds", "Nothing to show yet")
        self.LibraryExperimentalListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Experimental Branches", "Nothing to show yet")
        self.LibraryCustomListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Custom Builds", "Nothing to show yet")
        self.LibraryTab.layout().addWidget(self.LibraryToolBox)

        self.DownloadsToolBox = BaseToolBoxWidget(self)

        self.DownloadsStableListWidget = \
            self.DownloadsToolBox.add_list_widget(
                "Stable Releases", "No new builds available", False)
        self.DownloadsDailyListWidget = \
            self.DownloadsToolBox.add_list_widget(
                "Daily Builds", "No new builds available")
        self.DownloadsExperimentalListWidget = \
            self.DownloadsToolBox.add_list_widget(
                "Experimental Branches", "No new builds available")
        self.DownloadsTab.layout().addWidget(self.DownloadsToolBox)

        self.LibraryToolBox.setCurrentIndex(get_default_library_page())

        # Connect buttons
        self.SettingsButton.clicked.connect(self.show_settings_window)
        self.WikiButton.clicked.connect(lambda: webbrowser.open(
            "https://github.com/DotBow/Blender-Launcher/wiki"))
        self.MinimizeButton.clicked.connect(self.showMinimized)
        self.CloseButton.clicked.connect(self.close)

        self.StatusBar.setFont(self.font)
        self.statusbarLabel = QLabel()
        self.statusbarLabel.setIndent(8)
        self.NewVersionButton = QPushButton()
        self.NewVersionButton.hide()
        self.NewVersionButton.clicked.connect(lambda: webbrowser.open(
            "https://github.com/DotBow/Blender-Launcher/releases/latest"))
        self.statusbarVersion = QLabel(self.app.applicationVersion())
        self.StatusBar.addPermanentWidget(self.statusbarLabel, 1)
        self.StatusBar.addPermanentWidget(self.NewVersionButton)
        self.StatusBar.addPermanentWidget(self.statusbarVersion)

        # Draw library
        self.draw_library()

        # Setup tray icon context Menu
        quit_action = QAction("Quit", self)
        quit_action.triggered.connect(self.quit)
        hide_action = QAction("Hide", self)
        hide_action.triggered.connect(self.close)
        show_action = QAction("Show", self)
        show_action.triggered.connect(self._show)
        launch_favorite_action = QAction(
            QIcon(":resources/icons/favorite.svg"), "Blender", self)
        launch_favorite_action.triggered.connect(self.launch_favorite)

        tray_menu = QMenu()
        tray_menu.setFont(self.font)
        tray_menu.addAction(launch_favorite_action)
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addAction(quit_action)

        # Setup tray icon
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(
            QIcon(taskbar_icon_paths[get_taskbar_icon_color()]))
        self.tray_icon.setToolTip("Blender Launcher")
        self.tray_icon.activated.connect(self.tray_icon_activated)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.messageClicked.connect(self._show)
        self.tray_icon.show()

        # Forse style update
        self.style().unpolish(self.app)
        self.style().polish(self.app)

        # Show window
        if get_launch_minimized_to_tray() is False:
            self._show()

    def _show(self):
        self.activateWindow()
        self.show()
        self.set_status()
        self.show_signal.emit()

    def show_message(self, message, value=None):
        if value not in self.notification_pool:
            if value is not None:
                self.notification_pool.append(value)
            self.tray_icon.showMessage(
                "Blender Launcher", message,
                QIcon(taskbar_icon_paths[get_taskbar_icon_color()]), 10000)

    def launch_favorite(self):
        try:
            self.favorite.launch()
        except Exception:
            self.dlg = DialogWindow(self,
                                    text="Favorite build not found!",
                                    accept_text="OK",
                                    cancel_text=None)

    def tray_icon_activated(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            self._show()
        elif reason == QSystemTrayIcon.MiddleClick:
            self.launch_favorite()

    def quit(self):
        download_widgets = []

        download_widgets.extend(self.DownloadsStableListWidget.items())
        download_widgets.extend(self.DownloadsDailyListWidget.items())
        download_widgets.extend(self.DownloadsExperimentalListWidget.items())

        for widget in download_widgets:
            if widget.state == DownloadState.DOWNLOADING:
                self.dlg = DialogWindow(self,
                                        title="Warning",
                                        text="Download task in progress!<br>\
                    Are you sure you want to quit?",
                                        accept_text="Yes",
                                        cancel_text="No",
                                        icon=DialogIcon.WARNING)

                self.dlg.accepted.connect(self.destroy)
                return

        self.destroy()

    def destroy(self):
        if self.timer is not None:
            self.timer.cancel()

        self.tray_icon.hide()
        self.app.quit()

    def draw_library(self, clear=False):
        self.set_status("Reading local builds")

        if clear:
            self.timer.cancel()
            self.scraper.quit()
            self.DownloadsStableListWidget.clear()
            self.DownloadsDailyListWidget.clear()
            self.DownloadsExperimentalListWidget.clear()

        self.favorite = None

        self.LibraryStableListWidget.clear()
        self.LibraryDailyListWidget.clear()
        self.LibraryExperimentalListWidget.clear()

        self.library_drawer = LibraryDrawer(self)
        self.library_drawer.build_found.connect(self.draw_to_library)
        self.library_drawer.finished.connect(self.draw_downloads)
        self.library_drawer.start()

    def draw_downloads(self):
        for page in self.DownloadsToolBox.pages:
            page.set_info_label_text("Checking for new builds")

        self.app_state = AppState.CHECKINGBUILDS
        self.set_status("Checking for new builds")
        self.scraper = Scraper(self, self.manager)
        self.scraper.links.connect(self.draw_new_builds)
        self.scraper.new_bl_version.connect(self.set_version)
        self.scraper.error.connect(self.connection_error)
        self.scraper.start()

    def connection_error(self):
        set_locale()
        utcnow = strftime(('%H:%M'), localtime())
        self.set_status("Connection Error at " + utcnow)
        self.app_state = AppState.IDLE

        self.timer = threading.Timer(600.0, self.draw_downloads)
        self.timer.start()

    def draw_new_builds(self, builds):
        self.cashed_builds.clear()
        self.cashed_builds.extend(builds)

        library_widgets = []
        download_widgets = []

        library_widgets.extend(self.LibraryStableListWidget.items())
        library_widgets.extend(self.LibraryDailyListWidget.items())
        library_widgets.extend(self.LibraryExperimentalListWidget.items())

        download_widgets.extend(self.DownloadsStableListWidget.items())
        download_widgets.extend(self.DownloadsDailyListWidget.items())
        download_widgets.extend(self.DownloadsExperimentalListWidget.items())

        for widget in download_widgets:
            if widget.build_info in builds:
                builds.remove(widget.build_info)
            elif widget.state != DownloadState.DOWNLOADING:
                widget.destroy()

        for widget in library_widgets:
            if widget.build_info in builds:
                builds.remove(widget.build_info)

        for build_info in builds:
            self.draw_to_downloads(build_info)

        set_locale()
        utcnow = strftime(('%H:%M'), localtime())
        self.set_status("Last check at " + utcnow)
        self.app_state = AppState.IDLE
        for page in self.DownloadsToolBox.pages:
            page.set_info_label_text("No new builds available")

        self.timer = threading.Timer(600.0, self.draw_downloads)
        self.timer.start()

    def draw_from_cashed(self, build_info):
        if self.app_state == AppState.IDLE:
            if build_info in self.cashed_builds:
                i = self.cashed_builds.index(build_info)
                self.draw_to_downloads(self.cashed_builds[i])

    def draw_to_downloads(self, build_info):
        branch = build_info.branch

        if branch == 'stable':
            list_widget = self.DownloadsStableListWidget
        elif branch == 'daily':
            list_widget = self.DownloadsDailyListWidget
        else:
            list_widget = self.DownloadsExperimentalListWidget

        item = BaseListWidgetItem(build_info.commit_time)
        widget = DownloadWidget(self, list_widget, item, build_info)
        list_widget.add_item(item, widget)

    def draw_to_library(self, path):
        category = Path(path).parent.name

        if category == 'stable':
            list_widget = self.LibraryStableListWidget
        elif category == 'daily':
            list_widget = self.LibraryDailyListWidget
        elif category == 'experimental':
            list_widget = self.LibraryExperimentalListWidget
        elif category == 'custom':
            list_widget = self.LibraryCustomListWidget
        else:
            return

        item = BaseListWidgetItem()
        widget = LibraryWidget(self, item, path, list_widget)
        list_widget.insert_item(item, widget)

    def set_status(self, status=None):
        if status is not None:
            self.status = status

        self.statusbarLabel.setText("Status: {0}".format(self.status))

    def set_version(self, latest_tag):
        current_tag = self.app.applicationVersion()
        latest_ver = re.sub(r'\D', '', latest_tag)
        current_ver = re.sub(r'\D', '', current_tag)

        if int(latest_ver) > int(current_ver):
            if latest_tag not in self.notification_pool:
                self.NewVersionButton.setText(
                    "New version {0} is available".format(
                        latest_tag.replace('v', '')))
                self.NewVersionButton.show()
                self.show_message(
                    "New version of Blender Launcher is available!",
                    latest_tag)

    def show_settings_window(self):
        self.settings_window = SettingsWindow(self)

    def clear_temp(self):
        temp_folder = Path(get_library_folder()) / ".temp"
        self.remover = Remover(temp_folder)
        self.remover.start()

    def closeEvent(self, event):
        event.ignore()
        self.hide()
        self.close_signal.emit()

    def new_connection(self):
        self._show()
예제 #41
0
    def __init__(self):
        """Initial configuration."""
        super().__init__()

        # GLOBAL VARIABLES
        # graph variables
        self.graph = Graph()
        self.selected_node = None

        self.vertex_positions = []
        self.selected_vertex = None

        # offset of the mouse from the position of the currently dragged node
        self.mouse_drag_offset = None

        # position of the mouse; is updated when the mouse moves
        self.mouse_x = -1
        self.mouse_y = -1

        # variables for visualizing the graph
        self.node_radius = 20
        self.weight_rectangle_size = self.node_radius / 3

        self.arrowhead_size = 4
        self.arrow_separation = pi / 7

        self.selected_color = Qt.red
        self.regular_node_color = Qt.white
        self.regular_vertex_weight_color = Qt.black

        # limit the displayed length of labels for each node
        self.node_label_limit = 10

        # UI variables
        self.font_family = "Times New Roman"
        self.font_size = 18

        self.layout_margins = 8
        self.layout_item_spacing = 2 * self.layout_margins

        # canvas positioning - scale and translation
        self.scale = 1
        self.scale_coefficient = 1.1  # by how much the scale changes on scroll
        self.translation = [0, 0]

        # angle (in degrees) by which all of the nodes rotate
        self.node_rotation_angle = 15

        # TIMERS
        # runs the simulation 60 times a second (1000/60 ~= 16ms)
        self.simulation_timer = QTimer(
            interval=16, timeout=self.perform_simulation_iteration)

        # WIDGETS
        self.canvas = QFrame(self, minimumSize=QSize(0, 400))
        self.canvas_size = None
        self.canvas.resizeEvent = self.adjust_canvas_translation

        # toggles between directed/undirected graphs
        self.directed_toggle_button = QPushButton(
            text="undirected", clicked=self.toggle_directed_graph)

        # for showing the labels of the nodes
        self.labels_checkbox = QCheckBox(text="labels")

        # sets, whether the graph is weighted or not
        self.weighted_checkbox = QCheckBox(text="weighted",
                                           clicked=self.set_weighted_graph)

        # enables/disables forces (True by default - they're fun!)
        self.forces_checkbox = QCheckBox(text="forces", checked=True)

        # input of the labels and vertex weights
        self.input_line_edit = QLineEdit(
            enabled=self.labels_checkbox.isChecked(),
            textChanged=self.input_line_edit_changed)

        # displays information about the app
        self.about_button = QPushButton(text="?",
                                        clicked=self.show_help,
                                        sizePolicy=QSizePolicy(
                                            QSizePolicy.Fixed,
                                            QSizePolicy.Fixed))

        # imports/exports the current graph
        self.import_graph_button = QPushButton(text="import",
                                               clicked=self.import_graph)
        self.export_graph_button = QPushButton(text="export",
                                               clicked=self.export_graph)

        # WIDGET LAYOUT
        self.main_v_layout = QVBoxLayout(self, margin=0)
        self.main_v_layout.addWidget(self.canvas)

        self.option_h_layout = QHBoxLayout(self, margin=self.layout_margins)
        self.option_h_layout.addWidget(self.directed_toggle_button)
        self.option_h_layout.addSpacing(self.layout_item_spacing)
        self.option_h_layout.addWidget(self.weighted_checkbox)
        self.option_h_layout.addSpacing(self.layout_item_spacing)
        self.option_h_layout.addWidget(self.labels_checkbox)
        self.option_h_layout.addSpacing(self.layout_item_spacing)
        self.option_h_layout.addWidget(self.forces_checkbox)
        self.option_h_layout.addSpacing(self.layout_item_spacing)
        self.option_h_layout.addWidget(self.input_line_edit)

        self.io_h_layout = QHBoxLayout(self, margin=self.layout_margins)
        self.io_h_layout.addWidget(self.import_graph_button)
        self.io_h_layout.addSpacing(self.layout_item_spacing)
        self.io_h_layout.addWidget(self.export_graph_button)
        self.io_h_layout.addSpacing(self.layout_item_spacing)
        self.io_h_layout.addWidget(self.about_button)

        self.main_v_layout.addLayout(self.option_h_layout)
        self.main_v_layout.addSpacing(-self.layout_margins)
        self.main_v_layout.addLayout(self.io_h_layout)

        self.setLayout(self.main_v_layout)

        # WINDOW SETTINGS
        self.setWindowTitle('Graph Visualizer')
        self.setFont(QFont(self.font_family, self.font_size))
        self.setWindowIcon(QIcon("icon.ico"))
        self.show()

        # start the simulation
        self.simulation_timer.start()
예제 #42
0
    def paintEvent(self, event):
        """Paints the board."""
        painter = QPainter(self)

        painter.setRenderHint(QPainter.Antialiasing, True)

        painter.setPen(QPen(Qt.black, Qt.SolidLine))
        painter.setBrush(QBrush(Qt.white, Qt.SolidPattern))

        # bound the canvas area to not draw outside of it
        painter.setClipRect(0, 0, self.canvas.width(), self.canvas.height())

        # draw the background
        painter.drawRect(0, 0, self.canvas.width(), self.canvas.height())

        # transform and scale the painter accordingly
        painter.translate(self.translation[0], self.translation[1])
        painter.scale(self.scale, self.scale)

        # if the graph is weighted, reset the positions, since they will be re-drawn later on
        if self.graph.is_weighted():
            self.vertex_positions = []

        # draw vertices; has to be drawn before nodes, so they aren't drawn on top of them
        for node in self.graph.get_nodes():
            for neighbour, weight in node.get_neighbours().items():
                x1, y1, x2, y2 = node.get_x(), node.get_y(), neighbour.get_x(
                ), neighbour.get_y()

                # create a unit vector from the first to the second graph
                d = self.distance(x1, y1, x2, y2)
                ux, uy = (x2 - x1) / d, (y2 - y1) / d
                r = neighbour.get_radius()

                # if it's directed, draw the head of the arrow
                if self.graph.is_directed():
                    # in case there is a vertex going the other way, we will move the line up the circles by an angle,
                    # so there is separation between the vertices
                    if self.graph.does_vertex_exist(neighbour, node):
                        nx = -uy * r * sin(self.arrow_separation) + ux * r * (
                            1 - cos(self.arrow_separation))
                        ny = ux * r * sin(self.arrow_separation) + uy * r * (
                            1 - cos(self.arrow_separation))

                        x1, x2, y1, y2 = x1 + nx, x2 + nx, y1 + ny, y2 + ny

                    # the position of the head of the arrow
                    xa, ya = x1 + ux * (d - r), y1 + uy * (d - r)

                    # calculate the two remaining points of the arrow
                    # this is done the same way as the previous calculation (shift by vector)
                    d = self.distance(x1, y1, xa, ya)
                    ux_arrow, uy_arrow = (xa - x1) / d, (ya - y1) / d

                    # position of the base of the arrow
                    x, y = x1 + ux_arrow * (
                        d - self.arrowhead_size * 2), y1 + uy_arrow * (
                            d - self.arrowhead_size * 2)

                    # the normal vectors to the unit vector of the arrow head
                    nx_arrow, ny_arrow = -uy_arrow, ux_arrow

                    # draw the tip of the arrow, as the triangle
                    painter.setBrush(QBrush(Qt.black, Qt.SolidPattern))
                    painter.drawPolygon(
                        QPointF(xa, ya),
                        QPointF(x + nx_arrow * self.arrowhead_size,
                                y + ny_arrow * self.arrowhead_size),
                        QPointF(x - nx_arrow * self.arrowhead_size,
                                y - ny_arrow * self.arrowhead_size))

                # draw only one of the two vertices, if the graph is undirected
                if self.graph.is_directed() or id(node) < id(neighbour):
                    painter.drawLine(QPointF(x1, y1), QPointF(x2, y2))

                    if self.graph.is_weighted():
                        x_middle, y_middle = (x2 + x1) / 2, (y2 + y1) / 2

                        # if the graph is directed, the vertices are offset (so they aren't draw on top of each other),
                        # so we need to shift them back to be at the midpoint between the nodes
                        if self.graph.is_directed():
                            x_middle -= ux * r * (1 -
                                                  cos(self.arrow_separation))
                            y_middle -= uy * r * (1 -
                                                  cos(self.arrow_separation))

                        r = self.weight_rectangle_size

                        self.vertex_positions.append(
                            (x_middle, y_middle, (node, neighbour)))

                        # make the selected vertex rectangle background different, if it's selected (for aesthetics)
                        if self.selected_vertex is not None and node is self.selected_vertex[0] and neighbour is \
                                self.selected_vertex[1]:
                            painter.setBrush(
                                QBrush(self.selected_color, Qt.SolidPattern))
                        else:
                            painter.setBrush(
                                QBrush(self.regular_vertex_weight_color,
                                       Qt.SolidPattern))

                        # draw the square
                        square_rectangle = QRectF(x_middle - r, y_middle - r,
                                                  2 * r, 2 * r)
                        painter.drawRect(square_rectangle)

                        # adjust the length of the weight string, so the minus sign doesn't make the number smaller
                        length = len(str(weight)) - (1 if weight < 0 else 0)

                        painter.setFont(
                            QFont(self.font_family,
                                  self.font_size / (length * 3)))

                        # draw the value of the vertex (in white, so it's visible against the background)
                        painter.setPen(QPen(Qt.white, Qt.SolidLine))
                        painter.drawText(square_rectangle, Qt.AlignCenter,
                                         str(weight))
                        painter.setPen(QPen(Qt.black, Qt.SolidLine))

        # draw nodes
        for node in self.graph.get_nodes():
            # selected nodes are red to make them distinct; others are white
            if node is self.selected_node:
                painter.setBrush(QBrush(self.selected_color, Qt.SolidPattern))
            else:
                painter.setBrush(
                    QBrush(self.regular_node_color, Qt.SolidPattern))

            x, y, r = node.get_x(), node.get_y(), node.get_radius()

            painter.drawEllipse(QPointF(x, y), r, r)

            # only draw labels if the label checkbox is checked
            if self.labels_checkbox.isChecked():
                label = node.get_label()

                # scale font down, depending on the length of the label of the node
                painter.setFont(
                    QFont(self.font_family, self.font_size / len(label)))

                # draw the node label within the node dimensions
                painter.drawText(QRectF(x - r, y - r, 2 * r, 2 * r),
                                 Qt.AlignCenter, label)
예제 #43
0
    def check_conflicts(self):
        has_conflicts = False
        heading_font = QFont("Arial", 10)
        self.dialog = QDialog()
        connection = AuthServiceProxy("http://%s:%[email protected]:8374" %
                                      (rpcuser, rpcpassword))

        v_box = QVBoxLayout()

        same_iscc = connection.liststreamkeyitems('test_iscc', self.iscc)
        if len(same_iscc) > 0:
            heading = QLabel("Same ISCC:")
            heading.setFont(heading_font)
            v_box.addWidget(heading)
            has_conflicts = True
            for iscc_entry in same_iscc:
                v_box.addWidget(QLabel("Key: {}".format(iscc_entry['key'])))
                v_box.addWidget(
                    QLabel("Data: {}".format(
                        codecs.decode(iscc_entry['data'],
                                      'hex').decode('ascii'))))
                v_box.addWidget(
                    QLabel("Publishers: {}".format(", ".join(
                        self.get_node_alias(iscc_entry['publishers'])))))

        names = ['Meta', 'Content', 'Data', 'Instance']
        conflicts = [list(), list(), list(), list()]
        other_iscc = connection.liststreamitems('test_iscc')
        for iscc in other_iscc:
            key = iscc['key']
            if len(key.split('-')) != 4:
                continue
            if key != self.iscc:
                for i in range(4):
                    if key.split('-')[i] == self.iscc.split('-')[i]:
                        conflicts[i].append(key)
        for i, conflict_items in enumerate(conflicts):
            if len(conflict_items) > 0:
                has_conflicts = True
                heading = QLabel("Conflicts in {}-ID:".format(names[i]))
                heading.setFont(heading_font)
                v_box.addWidget(heading)
                for conflict_key in conflict_items:
                    for iscc_entry in connection.liststreamkeyitems(
                            'test_iscc', conflict_key):
                        v_box.addWidget(
                            QLabel("Key: {}".format(iscc_entry['key'])))
                        v_box.addWidget(
                            QLabel("Data: {}".format(
                                codecs.decode(iscc_entry['data'],
                                              'hex').decode('ascii'))))
                        v_box.addWidget(
                            QLabel("Publishers: {}".format(", ".join(
                                self.get_node_alias(
                                    iscc_entry['publishers'])))))

        if has_conflicts:
            tmp = QWidget()
            tmp.setLayout(v_box)
            scrollarea = QScrollArea()
            scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
            scrollarea.setWidget(tmp)
            main_v_box = QVBoxLayout()
            main_v_box.addWidget(scrollarea)

            button_h_box = QHBoxLayout()
            btn_add_extra = QPushButton("Add Extra")
            btn_add_extra.clicked.connect(self.do_add_extra)
            button_h_box.addWidget(btn_add_extra)
            btn_accept_conflict = QPushButton("Accept Conflict")
            btn_accept_conflict.clicked.connect(self.do_accept_conflict)
            button_h_box.addWidget(btn_accept_conflict)
            main_v_box.addLayout(button_h_box)

            self.dialog.setLayout(main_v_box)
            self.dialog.setWindowTitle('Conflicts')
            self.dialog.exec_()
        else:
            return True
예제 #44
0
 def __init__(self, main_window):
     super().__init__()
     self.main_window = main_window
     self.heading_font = QFont("Arial", 14)
     self.label_width = 50
     self.initUI()
예제 #45
0
    def init_ui(self):
        # 设置窗口主题、大小和背景图片
        self.setObjectName('MainWindow')
        self.setFixedSize(1300, 740)
        # 设置背景view
        self.bkgrd = QGraphicsView(self)
        self.bkgrd.setFixedSize(1280, 720)
        self.bkgrd.move(10, 10)
        self.bkgrd.setStyleSheet("background:transparent;border:none;")
        bkgrd_pixmap = QPixmap.fromImage((self.img_list[0]))
        bkgrd_pixmap.fromImage(self.img_list[0])
        self.bkgrd_scene = QGraphicsScene()
        self.bkgrd_scene.addItem(QGraphicsPixmapItem(bkgrd_pixmap))
        self.bkgrd.setScene(self.bkgrd_scene)
        # 小人
        self.character = QGraphicsView(self)
        self.character.setFixedSize(96, 144)
        self.character.move(0, 500)
        self.character.setStyleSheet("background:transparent;border:none;")
        cter_pixmap = QPixmap.fromImage((self.cter_img_list[0]))
        cter_pixmap.fromImage(self.img_list[0])
        self.cter_scene = QGraphicsScene()
        self.cter_scene.addItem(QGraphicsPixmapItem(cter_pixmap))
        self.character.setScene(self.cter_scene)
        # NPC
        self.npc = QGraphicsView(self)
        self.npc.setFixedSize(96, 96)
        self.npc.move(1050, 530)
        self.npc.setStyleSheet("background:transparent;border:none;")
        npc_pixmap = QPixmap.fromImage((self.npc_img_list[0]))
        self.npc_scene = QGraphicsScene()
        self.npc_scene.addItem(QGraphicsPixmapItem(npc_pixmap))
        self.npc.setScene(self.npc_scene)
        # 对话框
        self.dialog = QGraphicsView(self)
        self.dialog.setFixedSize(1248, 208)
        self.dialog.move(26, 496)
        dialog_pixmap = QPixmap.fromImage(self.dialog_img)
        palette = QPalette()
        palette.setBrush(self.dialog.backgroundRole(), QBrush(dialog_pixmap))
        self.dialog.setPalette(palette)
        self.dialog.hide()
        self.label = QLabel(self)
        self.label.setFont(QFont("宋体", 24, 40))
        self.label.setFixedSize(1000, 100)
        self.label.move(60, 496)
        self.label.setText("啦啦啦啦啦")
        self.label.hide()
        # 对话框下面的小三角
        self.tri = QGraphicsView(self)
        self.tri.setFixedSize(16, 16)
        self.tri.move(632, 696)
        self.tri.setStyleSheet("background:transparent;border:none;")
        tri_pixmap = QPixmap.fromImage(self.tri_img[0])
        self.tri_scene = QGraphicsScene()
        self.tri_scene.addItem(QGraphicsPixmapItem(tri_pixmap))
        self.tri.setScene(self.tri_scene)
        self.tri.hide()

        # 显示界面
        self.show()
예제 #46
0
 def drawText(self, event, qp):
     qp.setPen(QColor(168, 34, 3))
     qp.setFont(QFont('Decorative', 10))
     qp.drawText(event.rect(), Qt.AlignCenter, self.text)
예제 #47
0
    def setupUi(self, SplashScreen):
        if not SplashScreen.objectName():
            SplashScreen.setObjectName(u"SplashScreen")
        SplashScreen.resize(680, 400)
        self.centralwidget = QWidget(SplashScreen)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(10, 10, 10, 10)
        self.dropShadowFrame = QFrame(self.centralwidget)
        self.dropShadowFrame.setObjectName(u"dropShadowFrame")
        self.dropShadowFrame.setStyleSheet(
            u"QFrame{\n"
            "	\n"
            "	background-color: rgb(40, 44, 52);\n"
            "	color: rgb(150, 150, 150);\n"
            "	border-radius: 20px;\n"
            "}\n"
            "")
        self.dropShadowFrame.setFrameShape(QFrame.StyledPanel)
        self.dropShadowFrame.setFrameShadow(QFrame.Raised)
        self.label_title = QLabel(self.dropShadowFrame)
        self.label_title.setObjectName(u"label_title")
        self.label_title.setGeometry(QRect(0, 50, 661, 91))
        font = QFont()
        font.setFamily(u"El Messiri")
        font.setPointSize(30)
        self.label_title.setFont(font)
        self.label_title.setStyleSheet(u"color: rgb(189, 147, 249);")
        self.label_title.setAlignment(Qt.AlignCenter)
        self.label_description = QLabel(self.dropShadowFrame)
        self.label_description.setObjectName(u"label_description")
        self.label_description.setGeometry(QRect(0, 130, 661, 31))
        font1 = QFont()
        font1.setFamily(u"Poppins")
        font1.setPointSize(14)
        self.label_description.setFont(font1)
        self.label_description.setStyleSheet(u"color: rgb(150, 150, 150);")
        self.label_description.setAlignment(Qt.AlignCenter)
        self.progressBar = QProgressBar(self.dropShadowFrame)
        self.progressBar.setObjectName(u"progressBar")
        self.progressBar.setGeometry(QRect(50, 240, 561, 23))
        self.progressBar.setStyleSheet(
            u"QProgressBar {\n"
            "\n"
            "    background-color: rgb(98, 114, 164);\n"
            "    color: rgb(250, 250, 250);\n"
            "    border-style: none;\n"
            "    border-radius: 10px;\n"
            "    text-align: center;\n"
            "}\n"
            "QProgressBar::chunk{\n"
            "    border-radius: 10px;\n"
            "    background-color: qlineargradient(spread:pad, x1:0, y1:0.511364, x2:1, y2:0.523, stop:0 rgba(254, 121, 199, 255), stop:1 rgba(189, 147, 249, 255));\n"
            "}")
        self.progressBar.setValue(24)
        self.label_credit = QLabel(self.dropShadowFrame)
        self.label_credit.setObjectName(u"label_credit")
        self.label_credit.setGeometry(QRect(0, 340, 645, 31))
        self.label_credit2 = QLabel(self.dropShadowFrame)
        self.label_credit2.setObjectName(u"label_credit")
        self.label_credit2.setGeometry(QRect(20, 340, 401, 31))
        font1 = QFont()
        font1.setFamily(u"Poppins")
        font1.setPointSize(6)
        self.label_credit.setFont(font1)
        self.label_credit.setStyleSheet(u"color: rgb(150, 150, 150);")
        self.label_credit.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                       | Qt.AlignVCenter)
        self.label_credit2.setFont(font1)
        self.label_credit2.setStyleSheet(u"color: rgb(150, 150, 150);")
        self.label_credit2.setAlignment(Qt.AlignJustify | Qt.AlignVCenter)
        self.label_loading = QLabel(self.dropShadowFrame)
        self.label_loading.setObjectName(u"label_loading")
        self.label_loading.setGeometry(QRect(0, 270, 661, 31))
        font2 = QFont()
        font2.setFamily(u"Poppins")
        font2.setPointSize(12)
        self.label_loading.setFont(font2)
        self.label_loading.setStyleSheet(u"color: rgb(150, 150, 150);")
        self.label_loading.setAlignment(Qt.AlignCenter)

        self.verticalLayout.addWidget(self.dropShadowFrame)

        SplashScreen.setCentralWidget(self.centralwidget)

        self.retranslateUi(SplashScreen)

        QMetaObject.connectSlotsByName(SplashScreen)
예제 #48
0
def title_font():
    font = QFont()
    font.setPointSize(12)
    font.setStyleHint(QFont.Helvetica)
    return font
예제 #49
0
    def initUI(self):

        loadVideoBtn = QPushButton("Load Video", self)
        # loadVideoBtn.move(80, 100)
        loadVideoBtn.setGeometry(50, 100, 140, 40)
        loadVideoBtn.clicked.connect(self.getfile)

        # frameButton = QPushButton("Prepare Frames", self)
        # frameButton.move(80, 100)
        # frameButton.setGeometry(100, 100, 130, 40)
        # frameButton.clicked.connect(self.frameClicked)

        detectButton = QPushButton("Detect Location", self)
        # detectButton.move(80, 200)
        detectButton.setGeometry(50, 200, 140, 40)
        detectButton.clicked.connect(self.locationClicked)

        rotationButton = QPushButton("Rotate Direction", self)
        # rotationButton.move(80, 300)
        rotationButton.setGeometry(50, 300, 140, 40)
        rotationButton.clicked.connect(self.rotationClicked)

        self.blue = QLabel(self)
        self.blue.setText('Blue for CW')
        self.blue.setGeometry(50, 350, 250, 250)
        newfont = QFont("Times", 16, QFont.Bold)
        self.blue.setFont(newfont)
        self.blue.setStyleSheet('color: blue')

        self.green = QLabel(self)
        self.green.setText('Green for CCW')
        self.green.setGeometry(50, 380, 250, 250)
        newfont = QFont("Times", 16, QFont.Bold)
        self.green.setFont(newfont)
        self.green.setStyleSheet('color: green')

        self.red = QLabel(self)
        self.red.setText('Red for NR/Cplx')
        self.red.setGeometry(50, 410, 250, 250)
        newfont = QFont("Times", 16, QFont.Bold)
        self.red.setFont(newfont)
        self.red.setStyleSheet('color: red')

        self.text = QLabel(self)
        self.text.setText('Waiting for results...')
        self.text.setGeometry(50, 600, 250, 250)
        newfont = QFont("Times", 16, QFont.Bold)
        self.text.setFont(newfont)

        self.pic = QLabel(self)
        self.pic.setPixmap(QPixmap('background2.jpg'))
        self.pic.setGeometry(300, 0, 1200, 900)
        # pic.resize(800, 400)
        self.pic.setScaledContents(True)

        self.pic.show()  # You were missing this.

        self.statusBar()
        self.resize(1500, 900)
        self.center()

        self.setWindowTitle('Cell Rotation Platform Demo')
        self.show()
예제 #50
0
    def __init__(self):

        super().__init__()

        self.title = 'Donkey Kong'

        self.setStyleSheet("QWidget { background-color: %s}" %
                           QColor(0, 0, 0).name())
        self.resize(800, 600)
        self.center()
        self.setFixedSize(800, 600)

        self.playersName = []
        self.exist = False

        fontTB = QFont()
        fontTB.setFamily("Arcade Normal")
        fontTB.setPointSize(13)

        fontPlayerLabel = QFont()
        fontPlayerLabel.setFamily("Arcade Normal")
        fontPlayerLabel.setPointSize(8)

        fontBtn = QFont()
        fontBtn.setFamily("Arcade Normal")
        fontBtn.setPointSize(13)

        ####################################################################
        self.textLabel = QLabel(self)
        self.textLabel.move(140, 270)
        fontLabel = QFont()
        fontLabel.setFamily("Arcade Normal")
        fontLabel.setPointSize(10)
        self.textLabel.setStyleSheet('color: white;')
        self.textLabel.setFont(fontLabel)
        self.textLabel.setText(
            "Tournament for 4 players. \nEnter player names:")
        '''Player 1'''
        self.playerOneLabel = QLabel(self)
        self.playerOneLabel.move(20, 370)
        self.playerOneLabel.setStyleSheet('color: white;')
        self.playerOneLabel.setFont(fontPlayerLabel)
        self.playerOneLabel.setText("Player 1:")

        self.playerOne = QLineEdit(self)
        self.playerOne.resize(200, 50)
        self.playerOne.move(120, 350)
        self.playerOne.setStyleSheet(
            "QLineEdit { background-color: black; color: white; }")
        self.playerOne.setFont(fontTB)
        '''Player 2'''
        self.playerTwoLabel = QLabel(self)
        self.playerTwoLabel.move(20, 470)
        self.playerTwoLabel.setStyleSheet('color: white;')
        self.playerTwoLabel.setFont(fontPlayerLabel)
        self.playerTwoLabel.setText("Player 2:")

        self.playerTwo = QLineEdit(self)
        self.playerTwo.resize(200, 50)
        self.playerTwo.move(120, 450)
        self.playerTwo.setStyleSheet(
            "QLineEdit { background-color: black; color: white; }")
        self.playerTwo.setFont(fontTB)
        '''Player 3'''
        self.playerThreeLabel = QLabel(self)
        self.playerThreeLabel.move(400, 370)
        self.playerThreeLabel.setStyleSheet('color: white;')
        self.playerThreeLabel.setFont(fontPlayerLabel)
        self.playerThreeLabel.setText("Player 3:")

        self.playerThree = QLineEdit(self)
        self.playerThree.resize(200, 50)
        self.playerThree.move(500, 350)
        self.playerThree.setStyleSheet(
            "QLineEdit { background-color: black; color: white; }")
        self.playerThree.setFont(fontTB)
        '''Player 4 '''
        self.playerFourLabel = QLabel(self)
        self.playerFourLabel.move(400, 470)
        self.playerFourLabel.setStyleSheet('color: white;')
        self.playerFourLabel.setFont(fontPlayerLabel)
        self.playerFourLabel.setText("Player 4:")

        self.playerFour = QLineEdit(self)
        self.playerFour.resize(200, 50)
        self.playerFour.move(500, 450)
        self.playerFour.setStyleSheet(
            "QLineEdit { background-color: black; color: white; }")
        self.playerFour.setFont(fontTB)

        ################################################3
        self.playBtn = QPushButton("Play", self)
        self.playBtn.clicked.connect(self.startGame)
        self.playBtn.resize(200, 50)
        self.playBtn.move(250, 525)
        self.playBtn.setStyleSheet(
            "QPushButton:!hover { background-color: black; color: white;  }"
            "QPushButton:hover {background-color: black; color: red; }")
        self.playBtn.setFont(fontBtn)

        self.initUI()
예제 #51
0
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowTitle("Opvragen Webverkooporder")
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))

            self.setFont(QFont('Arial', 10))

            self.Keuze = QLabel()
            k0Edit = QComboBox()
            k0Edit.setFixedWidth(220)
            k0Edit.setFont(QFont("Arial", 10))
            k0Edit.setStyleSheet("color: black;  background-color: gainsboro")
            k0Edit.addItem(' Sorteersleutel voor zoeken')
            k0Edit.addItem('1. Alle Orders')
            k0Edit.addItem('2. Gefilterd op postcode')
            k0Edit.addItem('3. Gefilterd op achternaam')
            k0Edit.addItem('4. Gefilterd op ordernummer')
            k0Edit.addItem('5. Gefilterd op besteldatum')
            k0Edit.activated[str].connect(self.k0Changed)

            self.Zoekterm = QLabel()
            zktrmEdit = QLineEdit()
            zktrmEdit.setFixedWidth(220)
            zktrmEdit.setFont(QFont("Arial", 10))
            zktrmEdit.textChanged.connect(self.zktrmChanged)
            reg_ex = QRegExp('.*$')
            input_validator = QRegExpValidator(reg_ex, zktrmEdit)
            zktrmEdit.setValidator(input_validator)

            grid = QGridLayout()
            grid.setSpacing(20)

            lbl = QLabel()
            pixmap = QPixmap('./images/logos/verbinding.jpg')
            lbl.setPixmap(pixmap)
            grid.addWidget(lbl, 1, 0, 1, 2)

            logo = QLabel()
            pixmap = QPixmap('./images/logos/logo.jpg')
            logo.setPixmap(pixmap)
            grid.addWidget(logo, 1, 1, 1, 2, Qt.AlignRight)

            lbl1 = QLabel('Zoekterm')
            grid.addWidget(lbl1, 3, 0, 1, 1, Qt.AlignRight)
            grid.addWidget(zktrmEdit, 3, 1, 1, 2)
            grid.addWidget(k0Edit, 2, 1, 1, 2, Qt.AlignRight)

            self.setLayout(grid)
            self.setGeometry(500, 300, 150, 150)

            grid.addWidget(
                QLabel('\u00A9 2017 all rights reserved [email protected]'),
                5, 0, 1, 3, Qt.AlignCenter)

            applyBtn = QPushButton('Zoeken')
            applyBtn.clicked.connect(self.accept)

            grid.addWidget(applyBtn, 4, 2, 1, 1, Qt.AlignRight)
            applyBtn.setFont(QFont("Arial", 10))
            applyBtn.setFixedWidth(100)
            applyBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            closeBtn = QPushButton('Sluiten')
            closeBtn.clicked.connect(lambda: windowSluit(self, m_email))

            grid.addWidget(closeBtn, 4, 1, 1, 1, Qt.AlignRight)
            closeBtn.setFont(QFont("Arial", 10))
            closeBtn.setFixedWidth(100)
            closeBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")
예제 #52
0
    def setupLeftPanel(self):
        """ Setup the Left Panel containing the current active Image for MNIST as well as some image controls """
        # Example layout box, vertical
        left_panel_layout = QVBoxLayout()

        # Image display
        self.image_label = QLabel(self)
        left_panel_layout.addWidget(self.image_label)
        
        # Image controls
        image_controls_layout = QHBoxLayout()
        # Previous image
        previous_button = QPushButton('<----')
        previous_button.setFixedHeight(20)
        previous_button.clicked.connect(lambda x: self.previousImage())
        image_controls_layout.addWidget(previous_button)

        # Next image
        next_button = QPushButton('---->')
        next_button.setFixedHeight(20)
        next_button.clicked.connect(lambda x: self.nextImage())
        image_controls_layout.addWidget(next_button)

        left_panel_layout.addLayout(image_controls_layout)

        # Number label data
        number_labels_layout = QHBoxLayout()
        #number_labels_layout.setAlignment(Qt.AlignTop)

        number_font = QFont()
        number_font.setPointSize(40)
        number_font.setBold(True)
        # Dataset number (Actual) label
        self.dataset_label = QLabel()
        self.dataset_label.setAlignment(Qt.AlignHCenter)
        self.dataset_label.setStyleSheet("QLabel { color : green; }")
        self.dataset_label.setFont(number_font)
        number_labels_layout.addWidget(self.dataset_label)

        # Predicted label
        self.predicted_label = QLabel()
        self.predicted_label.setAlignment(Qt.AlignHCenter)
        self.predicted_label.setStyleSheet("QLabel { color : RoyalBlue; }")
        self.predicted_label.setFont(number_font)
        number_labels_layout.addWidget(self.predicted_label)

        self.updateDatasetImage()

        left_panel_layout.addLayout(number_labels_layout)

        # Number label data text description
        number_text_layout = QHBoxLayout()

        dataset_text_label = QLabel("Actual")
        dataset_text_label.setAlignment(Qt.AlignHCenter)
        number_text_layout.addWidget(dataset_text_label)

        predicted_text_label = QLabel("Predicted")
        predicted_text_label.setAlignment(Qt.AlignHCenter)
        number_text_layout.addWidget(predicted_text_label)

        left_panel_layout.addLayout(number_text_layout)

        image_filter_buttons_layout = QHBoxLayout()
        image_filter_buttons_layout.setAlignment(Qt.AlignLeft)

        show_all_radiobutton = QRadioButton()
        show_all_radiobutton.setText("Show All")
        show_all_radiobutton.setStyleSheet("QRadioButton::indicator::unchecked {  border-radius:5px;   border-style: solid; border-width:1px;; border-color: gray;}")
        show_all_radiobutton.clicked.connect(lambda x: self.filterAllowAllImages())

        show_only_incorrect_radiobutton = QRadioButton()
        show_only_incorrect_radiobutton.setText("Show Only Incorrect")
        show_only_incorrect_radiobutton.setStyleSheet("QRadioButton::indicator::unchecked {  border-radius:5px;   border-style: solid; border-width:1px;; border-color: gray;}")
        show_only_incorrect_radiobutton.clicked.connect(lambda x: self.filterAllowOnlyIncorrectImages())

        image_filter_buttons_layout.addWidget(show_all_radiobutton)
        image_filter_buttons_layout.addWidget(show_only_incorrect_radiobutton)
        

        left_panel_layout.addLayout(image_filter_buttons_layout)

        self.main_layout.addLayout(left_panel_layout)
예제 #53
0
    def displayWindow(self):

        self.setWindowTitle("Next Ticket Window")
        self.setGeometry(520, 100, 550, 260)
        self.setStyleSheet("""
            QWidget {
                background: rgb(0, 0, 72);
            }
            """)

        self.font1 = QFont()
        self.font1.setLetterSpacing(QFont.AbsoluteSpacing, 1.3)
        self.font1.setPixelSize(20)

        self.label1 = QLabel("Ticket Code", self)
        self.label1.setFixedSize(150, 40)
        mid_x1 = (self.width() - self.label1.width()) // 2
        self.label1.move(mid_x1, 10)
        self.label1.setFont(self.font1)
        self.label1.setStyleSheet("""
            QLabel {
                color:  rgba(255, 255, 255, 1);
                border: 1px solid rgba(255, 255, 255, 0.0);
                font-weight: 700;
                }
            """)
        self.label1.setAlignment(Qt.AlignCenter)

        font2 = QFont()
        font2.setLetterSpacing(QFont.AbsoluteSpacing, 1.3)
        font2.setPixelSize(60)

        self.label2 = QLabel("--------", self)
        self.label2.setFixedSize(350, 100)
        mid_x2 = (self.width() - self.label2.width()) // 2
        self.label2.move(mid_x2, 50)
        self.label2.setFont(font2)
        self.label2.setStyleSheet("""
            QLabel {
                color:  rgb(0, 0, 0);
                background: rgba(211, 141, 0, 1);
                border-radius: 10px;
                font-weight: 900;
                }
            """)
        self.label2.setAlignment(Qt.AlignCenter)

        self.label3 = QLabel("Proceed inside for", self)
        self.label3.setFixedSize(220, 40)
        mid_x3 = (self.width() - self.label3.width()) // 2
        self.label3.move(mid_x3, 170)
        self.label3.setFont(self.font1)
        self.label3.setStyleSheet("""
            QLabel {
                color:  rgba(255, 255, 255, 1);
                border: 1px solid rgba(255, 255, 255, 0.0);
                font-weight: 700;
                }
            """)
        self.label3.setAlignment(Qt.AlignCenter)

        font3 = QFont()
        font3.setPixelSize(30)
        font3.setLetterSpacing(QFont.AbsoluteSpacing, 1.3)

        self.label4 = QLabel("##########", self)
        self.label4.setFixedSize(320, 40)
        mid_x4 = (self.width() - self.label4.width()) // 2
        self.label4.move(mid_x4, 200)
        self.label4.setFont(font3)
        self.label4.setStyleSheet("""
            QLabel {
                color:  rgba(211, 141, 0, 1);
                border: 1px solid rgba(255, 255, 255, 0.0);
                font-weight: 700;
                }
            """)
        self.label4.setAlignment(Qt.AlignCenter)
예제 #54
0
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowTitle("Wijzigen Bedrijf-Verkoop")
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))

            self.setFont(QFont('Arial', 10))

            self.Bedrijfsnaam = QLabel()
            q3Edit = QLineEdit(mbedrnaam)
            q3Edit.setText(mbedrnaam)
            q3Edit.setFixedWidth(540)
            q3Edit.setFont(QFont("Arial", 10))
            q3Edit.textChanged.connect(self.q3Changed)
            reg_ex = QRegExp("^[^0-9]{1,50}$")
            input_validator = QRegExpValidator(reg_ex, q3Edit)
            q3Edit.setValidator(input_validator)

            self.Afdeling = QLabel()
            q16Edit = QLineEdit()
            q16Edit.setText(mafdeling)
            q16Edit.setFixedWidth(540)
            q16Edit.setFont(QFont("Arial", 10))
            q16Edit.textChanged.connect(self.q16Changed)
            reg_ex = QRegExp("^.{1,50}$")
            input_validator = QRegExpValidator(reg_ex, q16Edit)
            q16Edit.setValidator(input_validator)

            self.Rechtsvorm = QLabel()
            q5Edit = QLineEdit()
            q5Edit.setText(mrechtsvorm)
            q5Edit.setFixedWidth(100)
            q5Edit.setFont(QFont("Arial", 10))
            q5Edit.textChanged.connect(self.q5Changed)
            reg_ex = QRegExp("^[^0-9]{1,30}$")
            input_validator = QRegExpValidator(reg_ex, q5Edit)
            q5Edit.setValidator(input_validator)

            self.BTWnummer = QLabel()
            q2Edit = QLineEdit()
            q2Edit.setText(str(mbtwnr))
            q2Edit.setDisabled(True)
            q2Edit.setFixedWidth(170)
            q2Edit.setFont(QFont("Arial", 10))
            q2Edit.textChanged.connect(self.q2Changed)
            reg_ex = QRegExp("^[A-Za-z]{2}[0-9]{9}[Bb]{1}[0-9]{2}$")
            input_validator = QRegExpValidator(reg_ex, q2Edit)
            q2Edit.setValidator(input_validator)

            self.KvKnummer = QLabel()
            q4Edit = QLineEdit()
            q4Edit.setText(str(mkvknr))
            q4Edit.setFixedWidth(110)
            q4Edit.setDisabled(True)
            q4Edit.setFont(QFont("Arial", 10))
            q4Edit.textChanged.connect(self.q4Changed)
            reg_ex = QRegExp("^[0-9]{8}$")
            input_validator = QRegExpValidator(reg_ex, q4Edit)
            q4Edit.setValidator(input_validator)

            self.Straat = QLabel()
            q1Edit = QLineEdit()
            q1Edit.setText(mstraat)
            q1Edit.setFixedWidth(540)
            q1Edit.setDisabled(True)

            self.Huisnummer = QLabel()
            q7Edit = QLineEdit()
            q7Edit.setText(str(mhuisnr))
            q7Edit.setFixedWidth(60)
            q7Edit.setFont(QFont("Arial", 10))
            q7Edit.textChanged.connect(self.q7Changed)
            reg_ex = QRegExp("^[0-9]{1,5}$")
            input_validator = QRegExpValidator(reg_ex, q7Edit)
            q7Edit.setValidator(input_validator)

            self.Toevoeging = QLabel()
            q8Edit = QLineEdit('')
            q8Edit.setFixedWidth(80)
            q8Edit.setFont(QFont("Arial", 10))
            q8Edit.textChanged.connect(self.q8Changed)
            q8Edit.setText(mtoev)
            reg_ex = QRegExp("^[A-Za-z0-9-#]{0,10}")
            input_validator = QRegExpValidator(reg_ex, q8Edit)
            q8Edit.setValidator(input_validator)

            self.Postcode = QLabel()
            q6Edit = QLineEdit()
            q6Edit.setText(mpostcode)
            q6Edit.setFixedWidth(80)
            font = QFont("Arial", 10)
            font.setCapitalization(QFont.AllUppercase)
            q6Edit.setFont(font)
            q6Edit.textChanged.connect(self.q6Changed)
            reg_ex = QRegExp("^[0-9]{4}[A-Za-z]{2}$")
            input_validator = QRegExpValidator(reg_ex, q6Edit)
            q6Edit.setValidator(input_validator)

            self.Woonplaats = QLabel()
            q15Edit = QLineEdit()
            q15Edit.setText(mplaats)
            q15Edit.setFixedWidth(400)
            q15Edit.setDisabled(True)

            self.Telefoonnr = QLabel()
            q13Edit = QLineEdit('')
            q13Edit.setFixedWidth(120)
            q13Edit.setFont(QFont("Arial", 10))
            q13Edit.textChanged.connect(self.q13Changed)
            q13Edit.setText(mtelnr)
            reg_ex = QRegExp("^[0]{1}[0-9]{9}$")
            input_validator = QRegExpValidator(reg_ex, q13Edit)
            q13Edit.setValidator(input_validator)

            self.Bedrijfverkoopnummer = QLabel()
            q14Edit = QLineEdit()
            q14Edit.setText(str(mkopernr))
            q14Edit.setFixedWidth(120)
            q14Edit.setDisabled(True)
            q14Edit.setFont(QFont("Arial", 10))
            q14Edit.textChanged.connect(self.q14Changed)

            grid = QGridLayout()
            grid.setSpacing(20)

            lbl = QLabel()
            pixmap = QPixmap('./images/logos/verbinding.jpg')
            lbl.setPixmap(pixmap)
            grid.addWidget(lbl, 0, 0)

            logo = QLabel()
            pixmap = QPixmap('./images/logos/logo.jpg')
            logo.setPixmap(pixmap)
            grid.addWidget(logo, 0, 1, 1, 2, Qt.AlignRight)

            self.setFont(QFont('Arial', 10))
            grid.addWidget(QLabel('Bedrijf-Verkoop wijzigingen'), 0, 1)

            grid.addWidget(QLabel('                              *'), 1, 0)
            grid.addWidget(QLabel('Verplichte velden'), 1, 1)

            grid.addWidget(QLabel('Bedrijfsnaam           *'), 2, 0)
            grid.addWidget(q3Edit, 2, 1, 1, 3)

            grid.addWidget(QLabel('Afdelingsnaam/Kamer/\nKontaktpersoon'), 3,
                           0)
            grid.addWidget(q16Edit, 3, 1, 1, 3)

            grid.addWidget(QLabel('Rechtsvorm             *'), 4, 0)
            grid.addWidget(q5Edit, 4, 1)

            grid.addWidget(QLabel('BTWnummer   *'), 4, 1, 1, 1, Qt.AlignRight)
            grid.addWidget(q2Edit, 4, 2)

            grid.addWidget(QLabel('KvKnummer            *'), 5, 0)
            grid.addWidget(q4Edit, 5, 1)

            grid.addWidget(QLabel('Straat'), 6, 0)
            grid.addWidget(q1Edit, 6, 1, 1, 3)

            grid.addWidget(QLabel('Huisnummer           *'), 7, 0)
            grid.addWidget(q7Edit, 7, 1)

            grid.addWidget(QLabel('Toevoeging'), 7, 1, 1, 1, Qt.AlignRight)
            grid.addWidget(q8Edit, 7, 2)

            grid.addWidget(QLabel('Postcode Woonplaats *'), 8, 0)
            grid.addWidget(q6Edit, 8, 1)

            grid.addWidget(q15Edit, 8, 1, 1, 2, Qt.AlignRight)

            grid.addWidget(QLabel('Telefoonnummer     *'), 9, 0)
            grid.addWidget(q13Edit, 9, 1)

            grid.addWidget(QLabel('Bedrijf-Verkoopnummer'), 10, 0)
            grid.addWidget(q14Edit, 10, 1)

            grid.addWidget(
                QLabel('\u00A9 2017 all rights reserved [email protected]'),
                11, 1)

            cancelBtn = QPushButton('Sluiten')
            cancelBtn.clicked.connect(lambda: wijzWindow(self, m_email))

            applyBtn = QPushButton('Wijzigen')
            applyBtn.clicked.connect(self.accept)

            grid.addWidget(applyBtn, 10, 2, 1, 1, Qt.AlignRight)
            applyBtn.setFont(QFont("Arial", 10))
            applyBtn.setFixedWidth(100)
            applyBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            grid.addWidget(cancelBtn, 9, 2, 1, 1, Qt.AlignRight)
            cancelBtn.setFont(QFont("Arial", 10))
            cancelBtn.setFixedWidth(100)
            cancelBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            self.setLayout(grid)
            self.setGeometry(500, 100, 150, 150)
예제 #55
0
    def computeBounds(self):
        if self.myPhoto.isNull():
            self.myPhotoDestRect = QRect(0, 0, self.width(), self.height())
            self.viewCenter = (self.width() / 2, self.height() / 2)
            self.myPhotoRadius = 0
            self.myPhotoDiameter = 0
            for i in range(0, len(common.SamplingPattern)):
                self.samplePoints[i] = (0, 0)
                self.sampleAreaVisible[i] = []
            return

        # scale photo destination rect to fit photo on screen
        # scale by the scaling factor that requires the most scaling ( - 2 to fit in border )
        wRatio = self.width() / self.myPhoto.width()
        hRatio = self.height() / self.myPhoto.height()
        if wRatio <= hRatio:
            self.myPhotoDestRect.setWidth(self.myPhotoSrcRect.width() * wRatio - 2)
            self.myPhotoDestRect.setHeight(self.myPhotoSrcRect.height() * wRatio - 2)
        else:
            self.myPhotoDestRect.setWidth(self.myPhotoSrcRect.width() * hRatio - 2)
            self.myPhotoDestRect.setHeight(self.myPhotoSrcRect.height() * hRatio - 2)

        # center the photo dest rect
        self.myPhotoDestRect.moveTo(self.width() / 2 - self.myPhotoDestRect.width() / 2,
                                    self.height() / 2 - self.myPhotoDestRect.height() / 2)

        # NOTE - THESE ARE THE MOST IMPORTANT COMPUTATIONS FROM WHICH EVERYTHING ELSE IS PLOTTED
        self.viewCenter = (self.width() / 2, self.height() / 2)
        self.myPhotoRadius = self.myPhotoDestRect.height() / 2
        self.myPhotoDiameter = self.myPhotoRadius * 2
        self.myPhotoTopLeft = ((self.viewCenter[0] - self.myPhotoRadius), (self.viewCenter[1] - self.myPhotoRadius))

        # compute new scaled font size
        self.fontScaled = QFont('Courier New', self.myPhotoRadius * (1/(101-common.AppSettings["HUDTextScale"])))
        self.fontMetrics = QFontMetrics(self.fontScaled)

        # compute sampling pattern collision bounds
        ViewFisheye.SampleRadius = self.myPhotoRadius / 50
        hFOV = common.DataConfig["RadianceFOV"] / 2
        for i in range(0, len(common.SamplingPattern)):
            # compute sample bounds
            u, v = utility_angles.SkyCoord2FisheyeUV(common.SamplingPattern[i][0], common.SamplingPattern[i][1])
            x = self.myPhotoTopLeft[0] + (u * self.myPhotoDiameter)
            y = self.myPhotoTopLeft[1] + (v * self.myPhotoDiameter)
            self.samplePoints[i] = (x, y)
            # compute sampling pattern actual sampling areas (projected differential angle area)
            p1 = utility_angles.SkyCoord2FisheyeUV(common.SamplingPattern[i][0] - hFOV, common.SamplingPattern[i][1] - hFOV)
            p2 = utility_angles.SkyCoord2FisheyeUV(common.SamplingPattern[i][0] - hFOV, common.SamplingPattern[i][1] + hFOV)
            p3 = utility_angles.SkyCoord2FisheyeUV(common.SamplingPattern[i][0] + hFOV, common.SamplingPattern[i][1] + hFOV)
            p4 = utility_angles.SkyCoord2FisheyeUV(common.SamplingPattern[i][0] + hFOV, common.SamplingPattern[i][1] - hFOV)
            p1 = QPoint(self.myPhotoTopLeft[0] + (p1[0] * self.myPhotoDiameter), self.myPhotoTopLeft[1] + (p1[1] * self.myPhotoDiameter))
            p2 = QPoint(self.myPhotoTopLeft[0] + (p2[0] * self.myPhotoDiameter), self.myPhotoTopLeft[1] + (p2[1] * self.myPhotoDiameter))
            p3 = QPoint(self.myPhotoTopLeft[0] + (p3[0] * self.myPhotoDiameter), self.myPhotoTopLeft[1] + (p3[1] * self.myPhotoDiameter))
            p4 = QPoint(self.myPhotoTopLeft[0] + (p4[0] * self.myPhotoDiameter), self.myPhotoTopLeft[1] + (p4[1] * self.myPhotoDiameter))
            self.sampleAreaVisible[i] = [p1, p2, p3, p4]

        # compute compass lines
        self.compassTicks.clear()
        tickLength = self.myPhotoRadius / 90
        for angle in range(0, 360, 10):
            theta = 360 - ((angle + 270) % 360)  # angles eastward from North, North facing down
            rads = theta * math.pi / 180.0
            cx1 = (math.cos(rads) * (self.myPhotoRadius - tickLength)) + self.viewCenter[0]
            cy1 = (math.sin(rads) * (self.myPhotoRadius - tickLength)) + self.viewCenter[1]
            cx2 = (math.cos(rads) * self.myPhotoRadius) + self.viewCenter[0]
            cy2 = (math.sin(rads) * self.myPhotoRadius) + self.viewCenter[1]
            lx1 = (math.cos(rads) * (self.myPhotoRadius - tickLength*4)) + self.viewCenter[0] - self.fontMetrics.width(str(angle))/2
            ly1 = (math.sin(rads) * (self.myPhotoRadius - tickLength*4)) + self.viewCenter[1] - self.fontMetrics.height()/2
            self.compassTicks.append([cx1, cy1, cx2, cy2, lx1, ly1, angle])  # x1, y1, x2, y2, x1lbl, y1lbl, angle

        # compute new grid for debugging coordinates
        griddivs = 5
        gridwidth = int(round(self.myPhotoDiameter / griddivs))
        self.gridpoints = []
        self.gridUVs = []
        self.gridskycoords = []
        for r in range(1, griddivs):
            for c in range(1, griddivs):
                point = (self.myPhotoTopLeft[0] + (c * gridwidth), self.myPhotoTopLeft[1] + (r * gridwidth))
                self.gridpoints.append(point)
                u = (point[0] - self.myPhotoTopLeft[0]) / self.myPhotoDiameter
                v = (point[1] - self.myPhotoTopLeft[1]) / self.myPhotoDiameter
                self.gridUVs.append((u, v))
                t, p = utility_angles.FisheyeUV2SkyCoord(u, v)
                self.gridskycoords.append((t, p))

        # compute lens (ideal and actual) radii for drawn latitude ellipses along zenith
        self.lensIdealRadii.clear()
        self.lensRealRadii.clear()
        for alt in common.SamplingPatternAlts:
            # ideal lens
            u, v = utility_angles.SkyCoord2FisheyeUV(90, alt, lenswarp=False)
            x = self.myPhotoTopLeft[0] + (u * self.myPhotoDiameter)
            r = x - self.viewCenter[0]
            self.lensIdealRadii.append((r, alt))  # (radius, altitude)
            # warped lens
            u, v = utility_angles.SkyCoord2FisheyeUV(90, alt)
            x = self.myPhotoTopLeft[0] + (u * self.myPhotoDiameter)
            r = x - self.viewCenter[0]
            self.lensRealRadii.append((r, alt))   # (radius, altitude)

        # compute sun path screen points
        self.pathSun = QPainterPath()
        if len(self.sunPathPoints) > 0:
            azi, alt, dt = self.sunPathPoints[0]
            u, v = utility_angles.SkyCoord2FisheyeUV(azi, alt)
            x = self.myPhotoTopLeft[0] + (u * self.myPhotoDiameter)
            y = self.myPhotoTopLeft[1] + (v * self.myPhotoDiameter)
            self.pathSun.moveTo(x, y)
            for i in range(1, len(self.sunPathPoints)):
                azi, alt, dt = self.sunPathPoints[i]
                u, v = utility_angles.SkyCoord2FisheyeUV(azi, alt)
                x = self.myPhotoTopLeft[0] + (u * self.myPhotoDiameter)
                y = self.myPhotoTopLeft[1] + (v * self.myPhotoDiameter)
                self.pathSun.lineTo(x, y)

        # compute sun position screen point
        u, v = utility_angles.SkyCoord2FisheyeUV(self.sunPosition[0], self.sunPosition[1])
        x = self.myPhotoTopLeft[0] + (u * self.myPhotoDiameter)
        y = self.myPhotoTopLeft[1] + (v * self.myPhotoDiameter)
        self.sunPositionVisible = (x, y)

        # compute new mask
        self.mask = QPixmap(self.width(), self.height()).toImage()
예제 #56
0
# Z values
# bottom
ZGRIDHELIX = 40
ZSELECTION = 50
ZDESELECTOR = 60
ZWEDGEGIZMO = 100
ZPXIGROUP = 150
ZPARTITEM = 200
# top

# Part apperance
GRID_FILL = "#ffffff"

DEFAULT_PEN_WIDTH = 1
DEFAULT_ALPHA = 2
SELECTED_COLOR = '#5a8bff'
SELECTED_PEN_WIDTH = 2
SELECTED_ALPHA = 0

GRID_NUM_FONT = QFont(THE_FONT, 10, QFont.Bold)
USE_TEXT_COLOR = "#ffffff"
GRID_TEXT_COLOR = "#000000"

ACTIVE_STROKE = '#cccc00'
DEFAULT_GRID_DOT_COLOR = '#0000ff'
ACTIVE_GRID_DOT_COLOR = '#ff3333'  # item color

VHI_HINT_ACTIVE_STROKE = BLUE_STROKE
VHI_HINT_INACTIVE_STROKE = '#cccccc'
예제 #57
0
class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.threadpool = QThreadPool()
        self.displayWindow()
        self.callWindow()
        self.combo.activated.connect(lambda x: self.priorityStatus(x))
        self.df_index = 0
        self.cl_index = 0
        self.ev_index = 0
        self.ad_index = 0
        self.ot_index = 0
        self.curr_prio = 0
        self.called = []

    def displayWindow(self):

        self.setWindowTitle("Next Ticket Window")
        self.setGeometry(520, 100, 550, 260)
        self.setStyleSheet("""
            QWidget {
                background: rgb(0, 0, 72);
            }
            """)

        self.font1 = QFont()
        self.font1.setLetterSpacing(QFont.AbsoluteSpacing, 1.3)
        self.font1.setPixelSize(20)

        self.label1 = QLabel("Ticket Code", self)
        self.label1.setFixedSize(150, 40)
        mid_x1 = (self.width() - self.label1.width()) // 2
        self.label1.move(mid_x1, 10)
        self.label1.setFont(self.font1)
        self.label1.setStyleSheet("""
            QLabel {
                color:  rgba(255, 255, 255, 1);
                border: 1px solid rgba(255, 255, 255, 0.0);
                font-weight: 700;
                }
            """)
        self.label1.setAlignment(Qt.AlignCenter)

        font2 = QFont()
        font2.setLetterSpacing(QFont.AbsoluteSpacing, 1.3)
        font2.setPixelSize(60)

        self.label2 = QLabel("--------", self)
        self.label2.setFixedSize(350, 100)
        mid_x2 = (self.width() - self.label2.width()) // 2
        self.label2.move(mid_x2, 50)
        self.label2.setFont(font2)
        self.label2.setStyleSheet("""
            QLabel {
                color:  rgb(0, 0, 0);
                background: rgba(211, 141, 0, 1);
                border-radius: 10px;
                font-weight: 900;
                }
            """)
        self.label2.setAlignment(Qt.AlignCenter)

        self.label3 = QLabel("Proceed inside for", self)
        self.label3.setFixedSize(220, 40)
        mid_x3 = (self.width() - self.label3.width()) // 2
        self.label3.move(mid_x3, 170)
        self.label3.setFont(self.font1)
        self.label3.setStyleSheet("""
            QLabel {
                color:  rgba(255, 255, 255, 1);
                border: 1px solid rgba(255, 255, 255, 0.0);
                font-weight: 700;
                }
            """)
        self.label3.setAlignment(Qt.AlignCenter)

        font3 = QFont()
        font3.setPixelSize(30)
        font3.setLetterSpacing(QFont.AbsoluteSpacing, 1.3)

        self.label4 = QLabel("##########", self)
        self.label4.setFixedSize(320, 40)
        mid_x4 = (self.width() - self.label4.width()) // 2
        self.label4.move(mid_x4, 200)
        self.label4.setFont(font3)
        self.label4.setStyleSheet("""
            QLabel {
                color:  rgba(211, 141, 0, 1);
                border: 1px solid rgba(255, 255, 255, 0.0);
                font-weight: 700;
                }
            """)
        self.label4.setAlignment(Qt.AlignCenter)

    def callWindow(self):
        self.w2 = QWidget()
        self.w2.setStyleSheet("""
            QWidget {
                background: rgb(0, 0, 72);
            }
            """)
        self.w2.setWindowTitle("Caller Window")
        self.w2.setGeometry(520, 400, 550, 150)

        # Call next button
        self.call_button = QPushButton("Call Next Ticket", self.w2)
        self.call_button.setGeometry(130, 50, 350, 45)
        self.call_button.clicked.connect(self.onButtonClick)
        self.call_button.setFont(self.font1)
        self.call_button.setStyleSheet("""
            QPushButton {
                background: rgba(211, 141, 0, 1);
                border-radius: 10px;
                color: rgba(0, 0, 0, 1);
                font-weight: 700;
            }
            QPushButton:hover {
                background: rgba(255, 227, 15, 1);
            }
            """)
        mid_btn = (self.w2.width() - self.call_button.width()) // 2
        self.call_button.move(mid_btn, self.call_button.y())

        # Dropdown menu
        self.cb_label = QLabel("Set Priority", self.w2)
        self.cb_label.setFont(self.font1)
        self.cb_label.move(100, 20)
        self.cb_label.setStyleSheet("""
            QLabel {
                font-size: 17px;
                font-weight: 900;
                color: rgba(255, 255, 255, 1);
            }
            """)

        self.combo = QComboBox(self.w2)
        self.combo.addItems([
            "Default", "Clearance", "Evaluation", "Adding - Dropping",
            "Other Concerns"
        ])

        self.combo.setGeometry(220, 20, 230, 23)

        self.combo.setStyleSheet("""
            QComboBox {
                color: rgba(0, 0, 0, 1);
                background: rgba(255, 255, 255, 1);
                font-size: 13px;
            }
            QComboBox::item {
                background: #ffffff;
                border-top: 1px solid #dddddd;
                height: 20px;
            }

            QComboBox::item::selected {
                background: rgba(200, 200, 200, 1);
            }

            QComboBox:on {
                background: green;
            }
            """)

        # Notification
        self.font2 = QFont()
        self.font2.setLetterSpacing(QFont.AbsoluteSpacing, 1.4)
        self.label_notif = QLabel("* Ticket Status *", self.w2)
        self.label_notif.setFont(self.font2)
        self.label_notif.setFixedWidth(330)
        notif_x = (self.w2.width() // 2) - (self.label_notif.width() // 2)
        self.label_notif.move(notif_x, 100)
        self.label_notif.setAlignment(Qt.AlignCenter)
        self.label_notif.setStyleSheet("""
            QLabel {
                font-size: 10px;
                color: #ffffff;
            }
            """)

        self.w2.show()

    def onButtonClick(self):
        worker = Worker(self.magic)
        self.threadpool.start(worker)

    def priorityStatus(self, s):
        if s == 0:
            self.label_notif.setText("* Processing default tickets *")
        elif s == 1:
            self.label_notif.setText("* Processing clearance tickets *")
        elif s == 2:
            self.label_notif.setText("* Processing evaluation tickets *")
        elif s == 3:
            self.label_notif.setText("* Processing add - drop tickets *")
        else:
            self.label_notif.setText("* Processing other tickets *")

        self.curr_prio = s

    def showCurrentTicket(self, ticket):
        self.label2.setText(f"{ticket[0]}")
        self.setWindowTitle(f"Next Ticket Code: {ticket[0]}")

        if ticket[1] == "clear":
            self.label4.setText("Clearance")
        elif ticket[1] == "eval":
            self.label4.setText("Evaluation")
        elif ticket[1] == "add_drop":
            self.label4.setText("Adding / Dropping")
        else:
            self.label4.setText("Other concerns")

    def processPrio(self):
        def processTickets(f_label, p_label, index):
            tickets = [x for x in self.all_tickets if x[1] == f_label]

            if index < len(tickets):
                xx_ticket = tickets[index]

                if xx_ticket not in self.called:
                    self.showCurrentTicket(xx_ticket)
                    self.called.append(xx_ticket)
                else:
                    self.label_notif.setText(f"{xx_ticket} already called")

                return 1
            else:
                self.label_notif.setText(f"* {p_label} tickets done. ")
                return 0

        self.priorityStatus(self.curr_prio)

        if self.curr_prio == 0:
            f_label = None
            p_label = "Default"

            if self.df_index < len(self.all_tickets):
                df_ticket = self.all_tickets[self.df_index]

                if df_ticket not in self.called:
                    self.showCurrentTicket(df_ticket)
                    self.called.append(df_ticket)
                else:
                    self.label_notif.setText(f"{df_ticket} already called")

                self.df_index += 1
            else:
                self.label_notif.setText(f"{p_label} tickets done.")

        elif self.curr_prio == 1:
            f_label = "clear"
            p_label = "Clearance"

            to_add = processTickets(f_label, p_label, self.cl_index)
            self.cl_index += to_add

        elif self.curr_prio == 2:
            f_label = "eval"
            p_label = "Evaluation"

            to_add = processTickets(f_label, p_label, self.ev_index)
            self.ev_index += to_add

        elif self.curr_prio == 3:
            f_label = "add_drop"
            p_label = "Add - Drop"

            to_add = processTickets(f_label, p_label, self.ad_index)
            self.ad_index += to_add

        else:
            f_label = "others"
            p_label = "Other Concerns"
            ot_tickets = [x for x in self.all_tickets if x[1] == f_label]

            to_add = processTickets(f_label, p_label, self.ot_index)
            self.ot_index += to_add

    def magic(self):

        # Generating list of tickets from file including new ones
        self.all_tickets = []

        with open("ticket.log", "r") as fi:
            for entry in fi:
                if entry != "":
                    self.all_tickets.append(tuple(entry.strip().split(",")))

        self.processPrio()
예제 #58
0
    def initUI(self):
        menubar = self.menuBar()

        self.textEd = QTextEdit()
        self.textEd.setReadOnly(True)
        font = QFont()
        font.setPointSize(14)
        self.textEd.setFont(font)
        self.setCentralWidget(self.textEd)

        #config menu
        configMenu = menubar.addMenu("config")

        remoteSvrShowAct = QAction("显示远程服务器", self)
        remoteSvrShowAct.triggered.connect(self.remoteSvrShow)
        configMenu.addAction(remoteSvrShowAct)

        remoteSvrConfAct = QAction("配置远程服务器", self)
        remoteSvrConfAct.triggered.connect(self.remoteSvrConf)
        configMenu.addAction(remoteSvrConfAct)
        configMenu.addSeparator()

        localPGShowAct = QAction("浏览本地pgpass文件", self)
        localPGShowAct.triggered.connect(lambda: self.pgpassShow(None))
        configMenu.addAction(localPGShowAct)

        remotePGShowAct = QAction("浏览远程pgpass文件", self)
        remotePGShowAct.triggered.connect(
            lambda: self.pgpassShow(self.dbbk.remoteServer))
        configMenu.addAction(remotePGShowAct)
        configMenu.addSeparator()

        addLocalPGAct = QAction("添加本地pgpass记录", self)
        addLocalPGAct.triggered.connect(lambda: self.addPgpass(None))
        configMenu.addAction(addLocalPGAct)

        addRemotePGAct = QAction("添加远程pgpass记录", self)
        addRemotePGAct.triggered.connect(
            lambda: self.addPgpass(self.dbbk.remoteServer))
        configMenu.addAction(addRemotePGAct)

        #run menu
        optMenu = menubar.addMenu("run")

        backupAct = QAction("数据库备份", self)
        backupAct.triggered.connect(self.dbBackup)
        optMenu.addAction(backupAct)

        restoreAct = QAction("数据库恢复", self)
        restoreAct.triggered.connect(self.dbRestore)
        optMenu.addAction(restoreAct)
        optMenu.addSeparator()

        remoteBkAct = QAction("远程备份", self)
        remoteBkAct.triggered.connect(self.remoteBackup)
        optMenu.addAction(remoteBkAct)
        optMenu.addSeparator()

        structAct = QAction("表结构备份", self)
        structAct.triggered.connect(self.structBackup)
        optMenu.addAction(structAct)

        datasAct = QAction("表数据备份", self)
        datasAct.triggered.connect(self.datasBackup)
        optMenu.addAction(datasAct)
        optMenu.addSeparator()

        tableMenu = QMenu("单个表备份", self)
        optMenu.addMenu(tableMenu)

        tableAct = QAction("表备份", self)
        tableAct.triggered.connect(self.tableBackup)
        tableMenu.addAction(tableAct)

        tableStructAct = QAction("结构备份", self)
        tableStructAct.triggered.connect(self.tableStructBackup)
        tableMenu.addAction(tableStructAct)

        tableDataAct = QAction("数据备份", self)
        tableDataAct.triggered.connect(self.tableDataBackup)
        tableMenu.addAction(tableDataAct)

        self.setGeometry(700, 300, 400, 300)
        self.setWindowTitle('数据库备份工具')
        self.show()
예제 #59
0
    def callWindow(self):
        self.w2 = QWidget()
        self.w2.setStyleSheet("""
            QWidget {
                background: rgb(0, 0, 72);
            }
            """)
        self.w2.setWindowTitle("Caller Window")
        self.w2.setGeometry(520, 400, 550, 150)

        # Call next button
        self.call_button = QPushButton("Call Next Ticket", self.w2)
        self.call_button.setGeometry(130, 50, 350, 45)
        self.call_button.clicked.connect(self.onButtonClick)
        self.call_button.setFont(self.font1)
        self.call_button.setStyleSheet("""
            QPushButton {
                background: rgba(211, 141, 0, 1);
                border-radius: 10px;
                color: rgba(0, 0, 0, 1);
                font-weight: 700;
            }
            QPushButton:hover {
                background: rgba(255, 227, 15, 1);
            }
            """)
        mid_btn = (self.w2.width() - self.call_button.width()) // 2
        self.call_button.move(mid_btn, self.call_button.y())

        # Dropdown menu
        self.cb_label = QLabel("Set Priority", self.w2)
        self.cb_label.setFont(self.font1)
        self.cb_label.move(100, 20)
        self.cb_label.setStyleSheet("""
            QLabel {
                font-size: 17px;
                font-weight: 900;
                color: rgba(255, 255, 255, 1);
            }
            """)

        self.combo = QComboBox(self.w2)
        self.combo.addItems([
            "Default", "Clearance", "Evaluation", "Adding - Dropping",
            "Other Concerns"
        ])

        self.combo.setGeometry(220, 20, 230, 23)

        self.combo.setStyleSheet("""
            QComboBox {
                color: rgba(0, 0, 0, 1);
                background: rgba(255, 255, 255, 1);
                font-size: 13px;
            }
            QComboBox::item {
                background: #ffffff;
                border-top: 1px solid #dddddd;
                height: 20px;
            }

            QComboBox::item::selected {
                background: rgba(200, 200, 200, 1);
            }

            QComboBox:on {
                background: green;
            }
            """)

        # Notification
        self.font2 = QFont()
        self.font2.setLetterSpacing(QFont.AbsoluteSpacing, 1.4)
        self.label_notif = QLabel("* Ticket Status *", self.w2)
        self.label_notif.setFont(self.font2)
        self.label_notif.setFixedWidth(330)
        notif_x = (self.w2.width() // 2) - (self.label_notif.width() // 2)
        self.label_notif.move(notif_x, 100)
        self.label_notif.setAlignment(Qt.AlignCenter)
        self.label_notif.setStyleSheet("""
            QLabel {
                font-size: 10px;
                color: #ffffff;
            }
            """)

        self.w2.show()
예제 #60
0
 def font(self, prefix, size):
     """Return a QFont corresponding to the given prefix and size."""
     font = QFont(self.fontname[prefix])
     font.setPixelSize(size)
     return font