Exemplo n.º 1
0
def show():
    
    message = "{0}  {1} ".format(appinfo.appname, appinfo.version)
    pixmap = QPixmap(os.path.join(__path__[0], 'splash3.png'))
    if QApplication.desktop().screenGeometry().height() < 640:
        fontsize = 23
        pixmap = pixmap.scaledToHeight(240, Qt.SmoothTransformation)
    else:
        fontsize = 40

    splash = QSplashScreen(pixmap, Qt.SplashScreen)

    font = splash.font()
    font.setPixelSize(fontsize)
    font.setWeight(QFont.Bold)
    splash.setFont(font)

    splash.showMessage(message, Qt.AlignRight | Qt.AlignTop, Qt.white)
    splash.show()
    QApplication.processEvents()
    
    def hide():
        splash.deleteLater()
        app.appStarted.disconnect(hide)

    app.appStarted.connect(hide)
Exemplo n.º 2
0
    def initUI(self, gameboard): 

        self.setFixedSize((gameboard.width - 1)*blockSize, 40)
        
        moneypix = QPixmap(os.path.join('./Pictures/', "money.png"))
        moneyLabel = QLabel(self)
        moneyLabel.setPixmap(moneypix)
        moneyLabel.setFixedSize(moneypix.size())
        moneyLabel.move(5, 10)
        moneyLabel.show()
        
        
        wavepix = QPixmap(os.path.join('./Pictures/', "waves.png"))
        waveLabel = QLabel(self)
        waveLabel.setPixmap(wavepix)
        waveLabel.setFixedSize(wavepix.size())
        waveLabel.move((gameboard.width - 1)*blockSize / 2 - 82, 8)
        waveLabel.show()
        
        self.hearts = []
        heart = QPixmap(os.path.join('./Pictures/', 'heart.png'))
        self.heart_lost = QPixmap(os.path.join('./Pictures/', 'heart_lost.png'))
        i = 1
        
        while i <= self.parent.gameboard.startingLives:
            heartLabel = QLabel(self)
            heartLabel.setPixmap(heart)
            self.hearts.append([True, heartLabel])
            heartLabel.move((gameboard.width - 1)*blockSize - (2 + i * 12), 18)
            heartLabel.show()
            i += 1
        
        self.show()
Exemplo n.º 3
0
 def show_login_auth_code(self):
     img_data = self._my12306.auth_code_img('login')
     pixmap = QPixmap()
     pixmap.loadFromData(QByteArray(img_data))
     self.lb_auth_img.setPixmap(pixmap)
     self.lb_auth_img.setScaledContents(True)
     self.lb_auth_img.show()
Exemplo n.º 4
0
 def __cssLinkClass(self, icon, size=32):
     """
     Private method to generate a link class with an icon.
     
     @param icon icon to be included (QIcon)
     @param size size of the icon to be generated (integer)
     @return CSS class string (string)
     """
     cssString = \
         """a.{{0}} {{{{\n"""\
         """  padding-left: {0}px;\n"""\
         """  background: transparent url(data:image/png;base64,{1})"""\
         """ no-repeat center left;\n"""\
         """  font-weight: bold;\n"""\
         """}}}}\n"""
     pixmap = icon.pixmap(size, size)
     imageBuffer = QBuffer()
     imageBuffer.open(QIODevice.ReadWrite)
     if not pixmap.save(imageBuffer, "PNG"):
         # write a blank pixmap on error
         pixmap = QPixmap(size, size)
         pixmap.fill(Qt.transparent)
         imageBuffer.buffer().clear()
         pixmap.save(imageBuffer, "PNG")
     return cssString.format(
         size + 4,
         str(imageBuffer.buffer().toBase64(), encoding="ascii"))
Exemplo n.º 5
0
 def show_buy_auth_image(self):
     img_data = self._my12306.auth_code_img('passenger')
     pixmap = QPixmap()
     pixmap.loadFromData(QByteArray(img_data))
     self.lb_buy_img.setPixmap(pixmap)
     self.lb_buy_img.setScaledContents(True)
     self.lb_buy_img.show()
Exemplo n.º 6
0
    def setupScene(self):
        self.m_scene.setSceneRect(-300, -200, 600, 460)

        linearGrad = QLinearGradient(QPointF(-100, -100), QPointF(100, 100))
        linearGrad.setColorAt(0, Qt.darkGreen)#QColor(255, 255, 255))
        linearGrad.setColorAt(1, Qt.green)#QQColor(192, 192, 255))
        self.setBackgroundBrush(linearGrad)

        radialGrad = QRadialGradient(30, 30, 30)
        radialGrad.setColorAt(0, Qt.yellow)
        radialGrad.setColorAt(0.2, Qt.yellow)
        radialGrad.setColorAt(1, Qt.transparent)

        pixmap = QPixmap(60, 60)
        pixmap.fill(Qt.transparent)

        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.setBrush(radialGrad)
        painter.drawEllipse(0, 0, 60, 60)
        painter.end()

        self.m_lightSource = self.m_scene.addPixmap(pixmap)
        self.m_lightSource.setZValue(2)

        self.proto = ProtoObj(0, 0, 50, 50, self)
        self.proto.initObj()

        #self.m_items.append(self.proto.getObj()[0])
        self.m_scene.addItem(self.proto.getObj()[0])
Exemplo n.º 7
0
def run(image_path = None):
    # Global exceptions
    sys.excepthook = excepthook

    app = QApplication(sys.argv) 

    # Splash screen
    splash_pix = QPixmap('resources/splash.jpg')
    splash = QSplashScreen(splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    
    app.processEvents()
    
    # Load translation
    locale_code = SettingsModel().get('Language', 'code')
    if locale_code != "en_US": # Standard language
        # Standard translator for the generated GUI
        translator = QTranslator()
        translator.load('localization/' + locale_code + '.qm')
        app.installTranslator(translator)

        # Translator for various GUI elements
        translator_2 = QTranslator()
        translator_2.load('localization/' + locale_code + '_2.qm')
        app.installTranslator(translator_2)

    # Start
    m = Hitagi(image_path) # Pass image path
    
    splash.finish(m)
    sys.exit(app.exec())
Exemplo n.º 8
0
 def crop2Area(self):
     """Perform crop action on Area item
     """
     xb = int(self.area.pos().x())
     yb = int(self.area.pos().y())
     wb = int(self.area.rect().width())
     hb = int(self.area.rect().height())
     self.show_msg("Cropping area: {}, {}, {}, {}".format(xb, yb, wb, hb))
     box = self.leptonica.boxCreate(xb, yb, wb, hb)
     cropped = self.leptonica.pixClipRectangle(self.pix_image, box, None)
     qimage = lept.pix_to_qimage(self.leptonica, cropped)
     pixmap = QPixmap(qimage)
     if pixmap:
         self.scene.removeItem(self.image)
         del self.image
         self.image = self.scene.addPixmap(pixmap)
         self.scene.setSceneRect(QRectF(pixmap.rect()))
         self.pix_image = cropped
         self.image_width = self.leptonica.pixGetWidth(self.pix_image)
         self.image_height = self.leptonica.pixGetHeight(self.pix_image)
         self.removeSceneItem()
         self.show_msg("New image size: %dx%d, resolution %dx%d" %
                       (self.image_width,
                        self.image_height,
                        self.leptonica.pixGetXRes(self.pix_image),
                        self.leptonica.pixGetYRes(self.pix_image)
                        ))
Exemplo n.º 9
0
 def load_image(self, filename):
     """Load image to scene and create PIX
     """
     self.image_name = filename
     self.scene.clear()
     self.zoomTo1()
     # Read image with leptonica => create PIX structure and report image
     # size info
     self.pix_image = self.leptonica.pixRead(self.image_name.encode())
     self.image_width = self.leptonica.pixGetWidth(self.pix_image)
     self.image_height = self.leptonica.pixGetHeight(self.pix_image)
     self.show_msg("image size: %dx%d, resolution %dx%d" %
                   (self.image_width,
                    self.image_height,
                    self.leptonica.pixGetXRes(self.pix_image),
                    self.leptonica.pixGetYRes(self.pix_image)
                    ))
     self.box_data = []
     qimage = lept.pix_to_qimage(self.leptonica, self.pix_image)
     if not qimage:  # fallback solution
         pixmap = QPixmap(filename)
     else:
         pixmap = QPixmap(qimage)
     self.image = self.scene.addPixmap(pixmap)
     self.scene.setSceneRect(QRectF(pixmap.rect()))
     self.setWindowTitle(
         'Analyze & ORC image with tesseract and '
         'leptonica :: %s' %
         os.path.basename(
             self.image_name))
Exemplo n.º 10
0
    def draw_indicator(indicator: int):
        pixmap = QPixmap(24, 24)

        painter = QPainter(pixmap)
        w, h = pixmap.width(), pixmap.height()

        painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255))))

        pen = QPen(QColor("white"))
        pen.setWidth(2)
        painter.setPen(pen)

        font = util.get_monospace_font()
        font.setBold(True)
        font.setPixelSize(16)
        painter.setFont(font)

        f = QFontMetrics(painter.font())
        indicator_str = str(indicator) if indicator < 10 else "+"

        fw = f.width(indicator_str)
        fh = f.height()
        painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str)

        painter.end()
        return QIcon(pixmap)
Exemplo n.º 11
0
 def __grabRegion(self):
     """
     Private method to grab the selected region (i.e. do the snapshot).
     """
     pol = QPolygon(self.__selection)
     if not pol.isEmpty():
         self.__grabbing = True
         
         xOffset = self.__pixmap.rect().x() - pol.boundingRect().x()
         yOffset = self.__pixmap.rect().y() - pol.boundingRect().y()
         translatedPol = pol.translated(xOffset, yOffset)
         
         pixmap2 = QPixmap(pol.boundingRect().size())
         pixmap2.fill(Qt.transparent)
         
         pt = QPainter()
         pt.begin(pixmap2)
         if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff):
             pt.setRenderHints(
                 QPainter.Antialiasing |
                 QPainter.HighQualityAntialiasing |
                 QPainter.SmoothPixmapTransform,
                 True)
             pt.setBrush(Qt.black)
             pt.setPen(QPen(QBrush(Qt.black), 0.5))
             pt.drawPolygon(translatedPol)
             pt.setCompositionMode(QPainter.CompositionMode_SourceIn)
         else:
             pt.setClipRegion(QRegion(translatedPol))
             pt.setCompositionMode(QPainter.CompositionMode_Source)
         
         pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect())
         pt.end()
         
         self.grabbed.emit(pixmap2)
Exemplo n.º 12
0
    def update_item_info(self, name, data):
        merged = {}
        defaults = self.assets.items().get_item(name)
        if defaults is not None:
            merged.update(defaults[0])
        merged.update(data)

        item_info = "<html><body>"
        item_info += generate_item_info(merged)
        item_info += "</body></html>"
        self.ui.desc.setText(item_info)

        inv_icon = self.assets.items().get_item_icon(name)
        image = self.assets.items().get_item_image(name)

        if inv_icon is not None:
            inv_icon = self.assets.images().color_image(inv_icon, data)
            icon = QPixmap.fromImage(ImageQt(inv_icon))
        elif image is not None:
            image = self.assets.images().color_image(image, data)
            icon = QPixmap.fromImage(ImageQt(image))
        else:
            logging.warning("Unable to load image for %s", name)
            icon = QPixmap.fromImage(QImage.fromData(self.assets.items().missing_icon()))

        icon = self.scale_image_icon(icon, 64, 64)
        self.ui.icon.setPixmap(icon)
Exemplo n.º 13
0
 def set_color(self, color):
     if color != self._color:
         self._color = color
         self.colorChanged.emit(self._color)
         pixmap = QPixmap(self.iconSize())
         pixmap.fill(color)
         self.setIcon(QIcon(pixmap))
def drawIndicatorIcon(palette, style):
    pix = QPixmap(14, 14)
    pix.fill(Qt.transparent)
    branchOption = QStyleOption()
    #r = QRect(QPoint(0, 0), pix.size())
    branchOption.rect = QRect(2, 2, 9, 9) ## ### hardcoded in qcommonstyle.cpp
    branchOption.palette = palette
    branchOption.state = QStyle.State_Children

    p = QPainter()
    ## Draw closed state
    p.begin(pix)
    style.drawPrimitive(QStyle.PE_IndicatorBranch, branchOption, p)
    p.end()
    rc = QIcon(pix)
    rc.addPixmap(pix, QIcon.Selected, QIcon.Off)
    ## Draw opened state
    branchOption.state |= QStyle.State_Open
    pix.fill(Qt.transparent)
    p.begin(pix)
    style.drawPrimitive(QStyle.PE_IndicatorBranch, branchOption, p)
    p.end()

    rc.addPixmap(pix, QIcon.Normal, QIcon.On)
    rc.addPixmap(pix, QIcon.Selected, QIcon.On)
    return rc
Exemplo n.º 15
0
	def loadImageDropped(self, urlin):
		pix = QPixmap(urlin.toLocalFile())
		if pix.isNull():
			QMessageBox.critical(self, 'Error', 'An error occured while loading image')
			return False
		self.setPixmap(pix)
		return pix
Exemplo n.º 16
0
    def mousePressEvent(self, event):
        child = self.childAt(event.pos())
        if not child:
            return

        pixmap = QPixmap(child.pixmap())

        itemData = QByteArray()
        dataStream = QDataStream(itemData, QIODevice.WriteOnly)
        dataStream << pixmap << QPoint(event.pos() - child.pos())

        mimeData = QMimeData()
        mimeData.setData('application/x-dnditemdata', itemData)

        drag = QDrag(self)
        drag.setMimeData(mimeData)
        drag.setPixmap(pixmap)
        drag.setHotSpot(event.pos() - child.pos())

        tempPixmap = QPixmap(pixmap)
        painter = QPainter()
        painter.begin(tempPixmap)
        painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127))
        painter.end()

        child.setPixmap(tempPixmap)

        if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
            child.close()
        else:
            child.show()
            child.setPixmap(pixmap)
Exemplo n.º 17
0
    def drawRects(self, source, rectsTree, scale):
        """Draw rectangles in 'rectsTree' on 'source'.
        """
        pixmap = QPixmap(source)
        self.drawBackground(pixmap)

        def drawRect(node, parentHash):
            painter = QtGui.QPainter(pixmap)
            roi, param, tracking = node.data
            x, y, w, h = common.scaleRect(roi, scale)
            painter.setPen(param.color)
            funcTable = {
                self.FILL_MASK: self.fillMask,
                self.FILL_BLUR: self.fillBlur,
                self.FILL_IMAGE: self.fillImage,
                self.FILL_COLOR: self.fillColor,
                self.FILL_OUTLINE: self.fillOutline
                         }
            for fill, func in funcTable.iteritems():
                if param.fill == fill:
                    func(pixmap, painter, (x, y, w, h), param, source)
            if param.tracking:
                self.drawTracking(painter, tracking, scale)
            if param.showName:
                painter.drawText(x, y, param.name)
            return param.hash

        h, w = pixmap.height(), pixmap.width()
        rectsTree.map(None, drawRect)
        painter = QtGui.QPainter(source)
        painter.drawPixmap(0, 0, pixmap)
Exemplo n.º 18
0
Arquivo: gui.py Projeto: fqez/sandbox
    def checkText(self):
        img = cv2.imread(self.sourceImage)
        frec = self.cutFrec.text()
        n = self.order.text()
        if frec == "" or n == "":
            None
        else:
            n = int(n)
            frec = int(frec)
            if self.low_pass_radio_button.isChecked():
                result, fft = filter(img, frec, n, 'low')
                self.imgText2.setText("Low Pass Filter")
            else:
                result, fft = filter(img, frec, n)
                self.imgText2.setText("High Pass Filter")
            cv2.imwrite("results/filter.jpg", result.real)
            cv2.imwrite("results/fourier.jpg", fft.real)

            pixmap = QPixmap('results/filter.jpg')
            pixmap2 = QPixmap('results/fourier.jpg')
            pixmap = pixmap.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
            pixmap2 = pixmap2.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
            self.imgLabel2.fileName ='results/filter.jpg'
            self.imgLabel3.fileName = 'results/fourier.jpg'
            self.imgLabel2.setPixmap(pixmap)
            self.imgLabel3.setPixmap(pixmap2)
            self.imgText3.setText("Center FFT")
Exemplo n.º 19
0
    def init(self, ddir):
        """加载lolita.dat配置"""
        if not ddir or not isinstance(ddir, str): return
        try:
            if PY3: conf = json.loads(open(ddir + "/lolita.dat", "rb").read().decode())
            else: conf = json.loads(open(ddir + "/lolita.dat", "rb").read(), "utf-8")
            normal = conf.get("normal", "").format(DATA_DIR = ddir)
            move = conf.get("move", "").format(DATA_DIR = ddir)
            hover = conf.get("hover", "").format(DATA_DIR = ddir)
            press = conf.get("press", "").format(DATA_DIR = ddir)

            image = QPixmap(normal)
            self.resize(image.size())    # 设置窗口的大小
            self.setMinimumSize(image.size())
            self.setMaximumSize((image.size()))

            self.movies = {
                "normal": image,    # 普通
                "move": QPixmap(move),    # 移动
                "hover": QMovie(hover),    # 悬停(会动)
                "press": QPixmap(press),    # 按下
            }

            self._currentImage = image    # 当前的图形
            self.update()

            # 声音播放列表
            playList = conf.get("playList", [])
            self.player = LolitaPlayer(playList, ddir)
            self.player.setCurrentIndex(0)
        except Exception as e:
            self.close()
            traceback.print_exc(e)
Exemplo n.º 20
0
	def paintEvent(self,event=None):
	    
	    painter = QPainter(self)
	    pixmap=QPixmap(":/images/wheelfinal.png")

	    #painter.begin(self)
	    #painter.drawPixmap(QtCore.QRect(self.left, self.top, self.width, self.height), self.pixmap)
	    painter.drawPixmap(self.rect(), pixmap)
	    self.resize(pixmap.width(),pixmap.height())
	    
	    pen = QPen(Qt.red, 3)
	    painter.setPen(pen)
	    
	    painter.drawArc (self.disc_center-int(self.distance_from_center(self.points[0])) , 
	                        self.disc_center - int(self.distance_from_center (self.points[0])) , 
	                        2*int(self.distance_from_center(self.points[0])) , 
	                        2*int(self.distance_from_center(self.points[0])) , 
	                        int(16*self.hue_min) , 
	                        int(16*(self.hue_max-self.hue_min)))#arc joining point 0 and point 1
	    painter.drawLine(int(self.points[0][0]),int(self.points[0][1]),int(self.points[3][0]),int(self.points[3][1]))#line joining point 0 and point 3
	    painter.drawArc(self.disc_center-int(self.distance_from_center(self.points[2])) , 
	                        self.disc_center - int(self.distance_from_center (self.points[2])) , 
	                        2*int(self.distance_from_center(self.points[2])) , 
	                        2*int(self.distance_from_center(self.points[2])) , 
	                        int(16*self.hue_min) , 
	                        int(16*(self.hue_max-self.hue_min)))#arc joining point 2 and 3
	    painter.drawLine(int(self.points[1][0]),int(self.points[1][1]),int(self.points[2][0]),int(self.points[2][1]))#line joining point 1 and 2
	    
	    self.update()
Exemplo n.º 21
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
Exemplo n.º 22
0
 def on_imagesTree_currentItemChanged(self, current, previous):
     """
     Private slot to show a preview of the selected image.
     
     @param current current image entry (QTreeWidgetItem)
     @param previous old current entry (QTreeWidgetItem)
     """
     if current is None:
         return
     
     imageUrl = QUrl(current.text(1))
     if not imageUrl.host():
         imageUrl.setHost(QUrl(self.siteAddressLabel.text()).host())
         imageUrl.setScheme(QUrl(self.siteAddressLabel.text()).scheme())
     
     import Helpviewer.HelpWindow
     cache = Helpviewer.HelpWindow.HelpWindow.networkAccessManager().cache()
     if cache:
         cacheData = cache.data(imageUrl)
     else:
         cacheData = None
     pixmap = QPixmap()
     invalidPixmap = False
     scene = QGraphicsScene(self.imagePreview)
     if not cacheData:
         invalidPixmap = True
     else:
         pixmap.loadFromData(cacheData.readAll())
         if pixmap.isNull():
             invalidPixmap = True
     if invalidPixmap:
         scene.addText(self.tr("Preview not available."))
     else:
         scene.addPixmap(pixmap)
     self.imagePreview.setScene(scene)
Exemplo n.º 23
0
    def _setup_layout(self):
        main_layout = QVBoxLayout()
        content_layout = QHBoxLayout()
        splash_path = os.path.join(
            os.path.split(ilastik.__file__)[0], 'ilastik-splash.png'
        )
        splash_pixmap = QPixmap(splash_path)
        logo_label = QLabel()
        logo_label.setPixmap(splash_pixmap)
        content_layout.addWidget(logo_label)

        text_label = QLabel()
        text_label.setWordWrap(True)
        text_label.setTextFormat(Qt.RichText)
        text_label.setOpenExternalLinks(True)
        text_label.setText(about_text)
        content_layout.addWidget(text_label)

        btn_box = QDialogButtonBox(QDialogButtonBox.Ok)
        btn_box.accepted.connect(self.accept)

        main_layout.addLayout(content_layout)
        main_layout.addWidget(btn_box)

        self.setLayout(main_layout)
        self.setStyleSheet("background-color: white;")
        self.setWindowTitle('About ilastik')
        self.setFixedSize(splash_pixmap.width() * 2.5, splash_pixmap.height() * 1.05)
Exemplo n.º 24
0
    def SyncSize(self, size):
        self.resize(size)

        if self.width() == 1024 and self.height() == 738:
            self.WIDTH = self.BIG_WIDTH
            self.HEIGHT = self.BIG_HEIGHT
            self.ANCHOR_LEFT_X = self.BIG_ANCHOR_LEFT_X
            self.ANCHOR_RIGHT_X = self.BIG_ANCHOR_RIGHT_X
            self.ANCHOR_Y = self.BIG_ANCHOR_Y
            self.CLIP_WIDTH = self.BIG_CLIP_WIDTH
            self.CLIP_HEIGHT = self.BIG_CLIP_HEIGHT
            self.DIFF_LIMIT = self.BIG_DIFF_LIMIT
            self.btn_compare.setGeometry(611, 650, 100, 40)
            self.btn_toggle.setGeometry(715, 650, 100, 40)
        elif self.width() == 800 and self.height() == 600:
            self.WIDTH = self.SMALL_WIDTH
            self.HEIGHT = self.SMALL_HEIGHT
            self.ANCHOR_LEFT_X = self.SMALL_ANCHOR_LEFT_X
            self.ANCHOR_RIGHT_X = self.SMALL_ANCHOR_RIGHT_X
            self.ANCHOR_Y = self.SMALL_ANCHOR_Y
            self.CLIP_WIDTH = self.SMALL_CLIP_WIDTH
            self.CLIP_HEIGHT = self.SMALL_CLIP_HEIGHT
            self.DIFF_LIMIT = self.SMALL_DIFF_LIMIT
            self.btn_compare.setGeometry(472, 496, 100, 40)
            self.btn_toggle.setGeometry(576, 496, 100, 40)
        else:
            print("游戏窗体大小匹配错误")
            return

        self.pixmap = QPixmap(self.size())
        self.bgpixmap = QPixmap(self.width(), self.HEIGHT)
        self.bgpixmap.fill(QColor(0, 0, 255))
        self.label.setGeometry(0, self.ANCHOR_Y, self.width(), self.HEIGHT)
        self.label.setPixmap(self.bgpixmap)
Exemplo n.º 25
0
def getCombinedIcon(keys, cache=pixCache):
    """
    Module function to retrieve a symbolic link icon.

    @param keys list of names of icons (string)
    @param cache reference to the pixmap cache object (PixmapCache)
    @return the requested icon (QIcon)
    """
    height = width = 0
    pixmaps = []
    for key in keys:
        pix = cache.getPixmap(key)
        if not pix.isNull():
            height = max(height, pix.height())
            width = max(width, pix.width())
            pixmaps.append(pix)
    if pixmaps:
        pix = QPixmap(len(pixmaps) * width, height)
        pix.fill(Qt.transparent)
        painter = QPainter(pix)
        x = 0
        for pixmap in pixmaps:
            painter.drawPixmap(x, 0, pixmap.scaled(QSize(width, height)))
            x += width
        painter.end()
        icon = QIcon(pix)
    else:
        icon = QIcon()
    return icon
Exemplo n.º 26
0
    def Rotate(self):
        if(self.isHorizontal):
            self.symbol = QPixmap()
            self.symbol.load('ind2.png')
            self.symbol = self.symbol.scaledToHeight(100)
            self.resize(self.symbol.size())
            self.setPixmap(self.symbol)

            self.valueText.move(self.x() + 40, self.y() + 45)
            self.idLabel.move(self.x() + 40, self.y() + 25)
            self.valueText.setText(str(self.value) + ' H')

            self.nodeP.move(self.x() + 18, self.y())
            self.nodeS.move(self.x() + 18, self.y() + 90)

            self.isHorizontal = False

        else:
            self.symbol = QPixmap()
            self.symbol.load('ind.png')
            self.symbol = self.symbol.scaledToWidth(100)
            self.resize(self.symbol.size())
            self.setPixmap(self.symbol)

            self.valueText.move(self.x() + 30, self.y() + 40)
            self.idLabel.move(self.x() + 45, self.y())
            self.valueText.setText(str(self.value) + ' H')

            self.nodeP.move(self.x(), self.y() + 22)
            self.nodeS.move(self.x() + 90, self.y() + 22)

            self.isHorizontal = True
Exemplo n.º 27
0
 def image(cls, **kwargs):
     """
     Returns an image suitable for the palette.
     :rtype: QPixmap
     """
     # INITIALIZATION
     pixmap = QPixmap(kwargs['w'], kwargs['h'])
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     # INIT THE LINE
     p1 = QPointF(((kwargs['w'] - 54) / 2), kwargs['h'] / 2)
     p2 = QPointF(((kwargs['w'] - 54) / 2) + 54 - 2, kwargs['h'] / 2)
     line = QLineF(p1, p2)
     # CLACULATE HEAD COORDS
     angle = line.angle()
     p1 = QPointF(line.p2().x() + 2, line.p2().y())
     p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8)
     p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8)
     # INITIALIZE HEAD
     head = QPolygonF([p1, p2, p3])
     # DRAW EDGE LINE
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
     painter.drawLine(line)
     # DRAW EDGE HEAD
     painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
     painter.setBrush(QColor(0, 0, 0))
     painter.drawPolygon(head)
     return pixmap
Exemplo n.º 28
0
 def updateFilledCircle(self, s):
     size = s * self.zoom
     pixmap = QPixmap(self.width(), self.height())
     pixmap.fill(Qt.transparent)
     #painter filled ellipse
     p = QPalette()
     painter = QPainter()
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     brush = QBrush(p.link().color())
     painter.setBrush(brush)
     painter.setOpacity(0.4)
     painter.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter.end()
     #painter ellipse 2
     painter2 = QPainter()
     painter2.begin(pixmap)
     painter2.setRenderHint(QPainter.Antialiasing)
     pen2 = QPen(Qt.green)
     pen2.setWidth(1)
     painter2.setPen(pen2)
     painter2.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter2.end()
     
     self.ellipseLabel.setPixmap(QPixmap(pixmap))
     self.lastSize = s
Exemplo n.º 29
0
 def set_background(self, data):
     img = QImage()
     img.loadFromData(data)
     pixmap = QPixmap(img)
     if pixmap.isNull():
         return None
     return pixmap
Exemplo n.º 30
0
    def initUI(self):

        # Create the menubar and statusbar of the window
        menubar = self.menuBar()

        statusbar = self.statusBar()
        statusbar.showMessage('Ready')

        # Create the 'New Settings' Action
        newSettingsAct = QAction(QIcon('icons/newSettings.png'),
                                 '&New Settings', self)
        newSettingsAct.setShortcut('Ctrl+N')
        newSettingsAct.setStatusTip('Create New Settings')

        # Create the 'Import Settings' Action
        importSettingsAct = QAction(QIcon('icons/importSettings.png'),
                                    '&Import Settings', self)
        importSettingsAct.setShortcut('Ctrl+O')
        importSettingsAct.setStatusTip('Import Existing Settings')

        # Create the settings menu and add associated actions
        settingsMenu = menubar.addMenu('&Settings')
        settingsMenu.addAction(newSettingsAct)
        settingsMenu.addAction(importSettingsAct)

        # Create the settings toolbar and associated actions
        settingsToolbar = QToolBar(self)
        self.addToolBar(Qt.LeftToolBarArea, settingsToolbar)

        settingsToolbar.addAction(newSettingsAct)
        settingsToolbar.addAction(importSettingsAct)

        # Handle triggered 'NewSettings' and  'importSettings' actions
        newSettingsAct.triggered.connect(self.newSettingsTriggered)
        importSettingsAct.triggered.connect(self.importSettingsTriggered)

        # Set the attributes of the main window and display
        self.setGeometry(QDesktopWidget().availableGeometry())
        self.setWindowTitle('GARUDA - Sharp | Swift | Strong')
        # self.show()

        # Create and display contents of the main window
        main_widget = QWidget()
        self.setCentralWidget(main_widget)

        # create and display the 'GARUDA' logo
        garuda_footer_box = QHBoxLayout()

        garuda_logo_label = QLabel()
        garuda_logo_label.setPixmap(QPixmap('icons/garuda_small.png'))

        garuda_footer_box.addStretch()
        garuda_footer_box.addWidget(garuda_logo_label)

        # create and display widgets to read camera url
        self.camera_url_box = QHBoxLayout()

        camera_url_label = QLabel('Live Camera URL : ')
        self.camera_url_edit = QLineEdit()
        self.camera_capture_btn = QPushButton('Capture')

        self.camera_url_box.addWidget(camera_url_label)
        self.camera_url_box.addWidget(self.camera_url_edit)
        self.camera_url_box.addWidget(self.camera_capture_btn)

        # create and display widgets to display last seen component info
        last_comp_info_pane = QGroupBox('Last Component')

        last_comp_info_box = QVBoxLayout()

        self.last_comp_name_label = QLabel(
            'Component Name  :  {}'.format(None))
        self.last_comp_name_label.setStyleSheet('font-size: 12pt')
        self.last_comp_time_label = QLabel(
            'Timestamp             :  {}'.format(None))
        self.last_comp_time_label.setStyleSheet('font-size: 12pt')
        self.last_comp_match_label = QLabel(
            'Match Percent        :  {}'.format(None))
        self.last_comp_match_label.setStyleSheet('font-size: 12pt')

        last_comp_info_box.addWidget(self.last_comp_name_label)
        last_comp_info_box.addWidget(self.last_comp_time_label)
        last_comp_info_box.addWidget(self.last_comp_match_label)

        last_comp_info_pane.setLayout(last_comp_info_box)

        # Create and display widgets to display live camera feed and last comp info
        self.camera_comp_info_box = QHBoxLayout()

        self.camera_feed_viewer = cameraFeedWidget()
        self.camera_comp_info_box.addStretch(1)
        self.camera_comp_info_box.addWidget(self.camera_feed_viewer)
        self.camera_comp_info_box.addStretch(3)
        self.camera_comp_info_box.addWidget(last_comp_info_pane)
        self.camera_comp_info_box.addStretch(1)

        # create and display main window layout
        self.main_box = QVBoxLayout()

        self.main_box.addLayout(garuda_footer_box)
        self.main_box.addStretch(1)

        main_widget.setLayout(self.main_box)

        # Handle 'capture' button pressed event
        self.camera_capture_btn.pressed.connect(self.startCapture)
Exemplo n.º 31
0
class QtStraightProgressBar(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._initialized = self._redraw = False

    def setup(self,
              bounds = [0, 100], fillDirection = 6, border_thickness = 0,
              colors = [QColor('red'), QColor('black'), QColor('white')], capType = [0, 0]
        ):
        # Bounds
        self._bounds = bounds
        self._bounds_range = self._bounds[1] - self._bounds[0]
        self._old_value = self._current_value = self._bounds[0]
        # Fill Direction
        self._fill_direction = fillDirection
        if self._fill_direction == 4 or self._fill_direction == 6 or self._fill_direction == 46 or self._fill_direction == 64:
            self._horizontal = True
        elif self._fill_direction == 8 or self._fill_direction == 2 or self._fill_direction == 82 or self._fill_direction == 28:
            self._horizontal = False
        # Colors [0 = foreground color, 1 = background color, 2 = border color]
        self._colors = colors
        # Border Thickness
        self._border_thickness = border_thickness
        # Cap 0 = SquareCap, 1 = RoundCap, 2 = FlatCap
        self._cap = capType
        # Internal variables
        self._pen = QPen(self._colors[0], 0, Qt.SolidLine)
        self._pen.setCapStyle(Qt.FlatCap)
        # Ready Flag
        self._initialized = True

    def setValue(self, val):
        self._current_value = max(self._bounds[0], min(val, self._bounds[1]))

    def setGeometry(self, x, y, w, h):
        """ Override setGeometry method """
        super().setGeometry(x, y, w, h)
        if self._initialized:
            s = [self.width() - self._border_thickness, self.height() - self._border_thickness]
            self._length = s[0] if self._horizontal else s[1]
            self._thickness = s[1] if self._horizontal else s[0]
            self._mul = self._length / self._bounds_range
            if self._fill_direction == 46 or self._fill_direction == 64:
                self._mid = self.width() / 2
                self._mul /= 2
            elif self._fill_direction == 82 or self._fill_direction == 28:
                self._mid = self.height() / 2
                self._mul /= 2
        # Reset PixMaps
        self._background_buffer = QPixmap(self.width(), self.height())
        self._background_buffer.fill(Qt.transparent)
        self._foreground_t_buffer = QPixmap(self.width(), self.height())
        self._foreground_t_buffer.fill(Qt.transparent)
        self._foreground_buffer = QPixmap(self.width(), self.height())
        self._foreground_buffer.fill(Qt.transparent)

    def redraw(self):
        self._redraw = True

    def _drawLine(self, paint, ofst_start, ofst_end):
        self._pen.setCapStyle(Qt.FlatCap)
        paint.setPen(self._pen)
        # Draw Main Bar
        if self._horizontal == True:
            paint.drawLine(ofst_start, self.height() / 2, self.width() - ofst_end, self.height() / 2)
        else:
            paint.drawLine(self.width() / 2, ofst_start, self.width() / 2, self.height() - ofst_end)
        # Draw Round Caps
        if self._cap[0] == 1 or self._cap[1] == 1:
            self._pen.setCapStyle(Qt.RoundCap)
            paint.setPen(self._pen)
            if self._horizontal == True:
                if self._cap[0] == 1: paint.drawLine(ofst_start, self.height() / 2, self.width() / 2, self.height() / 2)
                if self._cap[1] == 1: paint.drawLine(self.width() / 2, self.height() / 2, self.width() - ofst_end, self.height() / 2)
            else:
                if self._cap[0] == 1: paint.drawLine(self.width() / 2, ofst_start, self.width() / 2, self.height() / 2)
                if self._cap[1] == 1: paint.drawLine(self.width() / 2, self.height() / 2, self.width() / 2, self.height() - ofst_end)

    def paintEvent(self, e):
        """ Override Paint Function """
        if not self._initialized: return
        paint = QPainter()
        # Draw the bar components
        if self._redraw:
            self._background_buffer.fill(Qt.transparent)
            self._foreground_t_buffer.fill(Qt.transparent)
            self._foreground_buffer.fill(Qt.transparent)
            ofst = [0, 0]
            for i in range(2): ofst[i] = 0 if self._cap[i] != 1 else (self.height() / 2 if self._horizontal else (self.width() / 2))
            # Draw Border
            paint.begin(self._background_buffer)
            paint.setRenderHint(QPainter.Antialiasing)
            if self._border_thickness > 0:
                self._pen.setColor(self._colors[2])
                self._pen.setWidthF(self._thickness + self._border_thickness)
                paint.setPen(self._pen)
                # Draw Bar
                self._drawLine(paint, ofst[0], ofst[1])
            # Draw Background and Foreground
            for i in range(2):
                self._pen.setColor(self._colors[1 - i])
                self._pen.setCapStyle(Qt.FlatCap)
                if i == 0:
                    self._pen.setWidthF(self._thickness)
                    for i in range(2): ofst[i] += self._border_thickness / 2 if self._cap[i] == 0 else 0
                    if self._fill_direction == 4 or self._fill_direction == 8:
                        self._ofst = 0 if self._cap[1] == 2 else self._border_thickness / 2
                    elif self._fill_direction == 6 or self._fill_direction == 2:
                        self._ofst = 0 if self._cap[0] == 2 else self._border_thickness / 2
                else:
                    paint.begin(self._foreground_t_buffer)
                    paint.setRenderHint(QPainter.Antialiasing)
                    if self._border_thickness > 0:
                        self._pen.setWidthF(self._thickness - 2)
                        ofst[0] += 1
                        ofst[1] += 1
                # Draw Bar
                self._drawLine(paint, ofst[0], ofst[1])
                paint.end()
                # Setup pen for updates
                self._pen.setWidth(self.height() if self._horizontal else self.width())
                self._pen.setCapStyle(Qt.FlatCap)
            # Update Flags
            self._redraw = False
        # Cut foreground to appropriate length
        if self._current_value != self._old_value:
            paint.begin(self._foreground_buffer)
            paint.setPen(self._pen)
            paint.setCompositionMode(QPainter.CompositionMode_SourceOver)
            paint.drawPixmap(0, 0, self.width(), self.height(), self._foreground_t_buffer)
            paint.setRenderHint(QPainter.Antialiasing)
            paint.setCompositionMode(QPainter.CompositionMode_Clear)
            delta = self._current_value - self._bounds[0]
            if self._fill_direction == 4:
                paint.drawLine(0, self.height() / 2, self.width() - self._ofst - self._mul * delta, self.height() / 2)
            elif self._fill_direction == 6:
                paint.drawLine(self._ofst + self._mul * delta, self.height() / 2, self.width(), self.height() / 2)
            elif self._fill_direction == 46 or self._fill_direction == 64:
                paint.drawLine(0, self.height() / 2, self._mid - self._mul * delta, self.height() / 2)
                paint.drawLine(self._mid + self._mul * delta, self.height() / 2, self.width(), self.height() / 2)
            elif self._fill_direction == 8:
                paint.drawLine(self.width() / 2, 0, self.width() / 2, self.height() - self._ofst - self._mul * delta)
            elif self._fill_direction == 2:
                paint.drawLine(self.width() / 2, self._ofst + self._mul * delta, self.width() / 2, self.height())
            elif self._fill_direction == 82 or self._fill_direction == 28:
                paint.drawLine(self.width() / 2, 0, self.width() / 2, self._mid - self._mul * delta)
                paint.drawLine(self.width() / 2, self._mid + self._mul * delta, self.width() / 2, self.height())
            paint.setCompositionMode(QPainter.CompositionMode_SourceOver)
            paint.setPen(self._pen)
            paint.end()
            # Update Flags
            self._old_value = self._current_value

        paint.begin(self)
        paint.setRenderHint(QPainter.SmoothPixmapTransform)
        paint.drawPixmap(0, 0, self.width(), self.height(), self._background_buffer)
        if self._current_value > self._bounds[0]:
            paint.drawPixmap(0, 0, self.width(), self.height(), self._foreground_buffer)
        paint.end()
Exemplo n.º 32
0
def widgets(P, W):
    #widgets
    W.ctLabel = QLabel('CUT TYPE')
    W.ctGroup = QButtonGroup(W)
    W.cExt = QRadioButton('EXTERNAL')
    W.cExt.setChecked(True)
    W.ctGroup.addButton(W.cExt)
    W.cInt = QRadioButton('INTERNAL')
    W.ctGroup.addButton(W.cInt)
    W.koLabel = QLabel('KERF')
    W.kOffset = QPushButton('OFFSET')
    W.kOffset.setCheckable(True)
    W.xsLabel = QLabel('X ORIGIN')
    W.xsEntry = QLineEdit(objectName='xsEntry')
    W.ysLabel = QLabel('Y ORIGIN')
    W.ysEntry = QLineEdit(objectName='ysEntry')
    W.liLabel = QLabel('LEAD IN')
    W.liEntry = QLineEdit(objectName='liEntry')
    W.loLabel = QLabel('LEAD OUT')
    W.loEntry = QLineEdit(objectName='loEntry')
    W.wLabel = QLabel('WIDTH')
    W.wEntry = QLineEdit()
    W.hLabel = QLabel('HEIGHT')
    W.hEntry = QLineEdit()
    W.rButton = QPushButton('RADIUS')
    W.rEntry = QLineEdit()
    W.aLabel = QLabel('ANGLE')
    W.aEntry = QLineEdit()
    W.preview = QPushButton('PREVIEW')
    W.add = QPushButton('ADD')
    W.undo = QPushButton('UNDO')
    W.lDesc = QLabel('CREATING GUSSET')
    W.iLabel = QLabel()
    pixmap = QPixmap('{}conv_gusset_l.png'.format(P.IMAGES)).scaledToWidth(196)
    W.iLabel.setPixmap(pixmap)
    #alignment and size
    rightAlign = ['ctLabel', 'koLabel', 'xsLabel', 'xsEntry', 'ysLabel', 'ysEntry', \
                  'liLabel', 'liEntry', 'loLabel', 'loEntry', 'wLabel', 'wEntry', \
                  'hLabel', 'hEntry', 'rEntry', 'aLabel', 'aEntry']
    centerAlign = ['lDesc']
    rButton = ['cExt', 'cInt']
    pButton = ['preview', 'add', 'undo', 'rButton', 'kOffset']
    for widget in rightAlign:
        W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        W[widget].setFixedWidth(80)
        W[widget].setFixedHeight(24)
    for widget in centerAlign:
        W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
        W[widget].setFixedWidth(240)
        W[widget].setFixedHeight(24)
    for widget in rButton:
        W[widget].setFixedWidth(80)
        W[widget].setFixedHeight(24)
    for widget in pButton:
        W[widget].setFixedWidth(80)
        W[widget].setFixedHeight(24)
    #starting parameters
    W.add.setEnabled(False)
    W.undo.setEnabled(False)
    W.liEntry.setText('{}'.format(P.leadIn))
    W.loEntry.setText('{}'.format(P.leadOut))
    W.xsEntry.setText('{}'.format(P.xSaved))
    W.ysEntry.setText('{}'.format(P.ySaved))
    W.rEntry.setText('0')
    W.aEntry.setText('90.0')
    if not W.liEntry.text() or float(W.liEntry.text()) == 0:
        W.kOffset.setChecked(False)
        W.kOffset.setEnabled(False)
    P.conv_undo_shape()
    #connections
    W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W))
    W.cExt.toggled.connect(lambda: auto_preview(P, W))
    W.kOffset.toggled.connect(lambda: auto_preview(P, W))
    W.rButton.pressed.connect(lambda: rad_button_pressed(P, W, W.sender()))
    W.preview.pressed.connect(lambda: preview(P, W))
    W.add.pressed.connect(lambda: add_shape_to_file(P, W))
    W.undo.pressed.connect(lambda: undo_pressed(P, W))
    entries = [
        'xsEntry', 'ysEntry', 'liEntry', 'loEntry', 'wEntry', 'hEntry',
        'rEntry', 'aEntry'
    ]
    for entry in entries:
        W[entry].textChanged.connect(lambda: entry_changed(P, W, W.sender()))
        W[entry].editingFinished.connect(lambda: auto_preview(P, W))
    #add to layout
    if P.landscape:
        W.entries.addWidget(W.ctLabel, 0, 0)
        W.entries.addWidget(W.cExt, 0, 1)
        W.entries.addWidget(W.cInt, 0, 2)
        W.entries.addWidget(W.koLabel, 0, 3)
        W.entries.addWidget(W.kOffset, 0, 4)
        W.entries.addWidget(W.xsLabel, 1, 0)
        W.entries.addWidget(W.xsEntry, 1, 1)
        W.entries.addWidget(W.ysLabel, 2, 0)
        W.entries.addWidget(W.ysEntry, 2, 1)
        W.entries.addWidget(W.liLabel, 3, 0)
        W.entries.addWidget(W.liEntry, 3, 1)
        W.entries.addWidget(W.loLabel, 4, 0)
        W.entries.addWidget(W.loEntry, 4, 1)
        W.entries.addWidget(W.wLabel, 5, 0)
        W.entries.addWidget(W.wEntry, 5, 1)
        W.entries.addWidget(W.hLabel, 6, 0)
        W.entries.addWidget(W.hEntry, 6, 1)
        W.entries.addWidget(W.rButton, 7, 0)
        W.entries.addWidget(W.rEntry, 7, 1)
        W.entries.addWidget(W.aLabel, 8, 0)
        W.entries.addWidget(W.aEntry, 8, 1)
        for r in range(9, 12):
            W['s{}'.format(r)] = QLabel('')
            W['s{}'.format(r)].setFixedHeight(24)
            W.entries.addWidget(W['s{}'.format(r)], r, 0)
        W.entries.addWidget(W.preview, 12, 0)
        W.entries.addWidget(W.add, 12, 2)
        W.entries.addWidget(W.undo, 12, 4)
        W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
        W.entries.addWidget(W.iLabel, 2, 2, 7, 3)
    else:
        W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
        W.entries.addWidget(W.ctLabel, 1, 0)
        W.entries.addWidget(W.cExt, 1, 1)
        W.entries.addWidget(W.cInt, 1, 2)
        W.entries.addWidget(W.koLabel, 1, 3)
        W.entries.addWidget(W.kOffset, 1, 4)
        W.entries.addWidget(W.xsLabel, 2, 0)
        W.entries.addWidget(W.xsEntry, 2, 1)
        W.entries.addWidget(W.ysLabel, 2, 2)
        W.entries.addWidget(W.ysEntry, 2, 3)
        W.entries.addWidget(W.liLabel, 3, 0)
        W.entries.addWidget(W.liEntry, 3, 1)
        W.entries.addWidget(W.loLabel, 3, 2)
        W.entries.addWidget(W.loEntry, 3, 3)
        W.entries.addWidget(W.wLabel, 4, 0)
        W.entries.addWidget(W.wEntry, 4, 1)
        W.entries.addWidget(W.hLabel, 5, 0)
        W.entries.addWidget(W.hEntry, 5, 1)
        W.entries.addWidget(W.rButton, 6, 0)
        W.entries.addWidget(W.rEntry, 6, 1)
        W.entries.addWidget(W.aLabel, 7, 0)
        W.entries.addWidget(W.aEntry, 7, 1)
        W.s8 = QLabel('')
        W.s8.setFixedHeight(24)
        W.entries.addWidget(W.s8, 8, 0)
        W.entries.addWidget(W.preview, 9, 0)
        W.entries.addWidget(W.add, 9, 2)
        W.entries.addWidget(W.undo, 9, 4)
        W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
        W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
    W.wEntry.setFocus()
class DrawCircle(QWidget):
    def __init__(self):
        super(DrawCircle, self).__init__()
        self.board = QPixmap(1000, 500)
        self.board.fill(Qt.white)
        # setMouseTracking设置为False,否则不按下鼠标时也会跟踪鼠标事件
        self.setMouseTracking(False)
        self.painter = QPainter()
        # 设置起点和终点,并设置标志位以控制打点
        self.radius = 0
        self.center_x = 0
        self.center_y = 0
        self.center_flag = False
        self.xr = 0
        self.yr = 0

    def paintEvent(self, paintEvent):
        self.painter.begin(self)
        self.painter.drawPixmap(0, 0, self.board)
        self.painter.end()

    def paintPoints(self, x, y):
        self.paintPoint(self.center_x + x, self.center_y + y)
        self.paintPoint(self.center_x - x, self.center_y + y)
        self.paintPoint(self.center_x + x, self.center_y - y)
        self.paintPoint(self.center_x - x, self.center_y - y)
        self.paintPoint(self.center_x + y, self.center_y + x)
        self.paintPoint(self.center_x - y, self.center_y + x)
        self.paintPoint(self.center_x + y, self.center_y - x)
        self.paintPoint(self.center_x - y, self.center_y - x)

    def paintPoint(self, x, y):
        self.painter.begin(self.board)
        self.painter.setPen(QPen(Qt.black, 6))
        self.painter.drawPoint(x, y)
        self.painter.end()
        self.update()

    def mouseMoveEvent(self, event):
        if not self.center_flag:
            self.center_x = event.pos().x()
            self.center_y = event.pos().y()
            self.paintPoint(self.center_x, self.center_y)
            self.center_flag = True
        else:
            self.xr = event.pos().x()
            self.yr = event.pos().y()
            self.radius = math.sqrt((self.xr - self.center_x)**2 +
                                    (self.yr - self.center_y)**2)
            self.midPointDrawCircle()

    def clearBoard(self):
        self.board.fill(Qt.white)
        self.update()
        # 回到初始状态
        self.center_x = 0
        self.center_y = 0
        self.radius = 0
        self.center_flag = False
        self.xr = 0
        self.yr = 0

    def mouseDoubleClickEvent(self, event):
        self.clearBoard()

    def midPointDrawCircle(self):
        x = 0
        y = self.radius
        delta = 1 - self.radius
        self.paintPoints(x, y)
        while x < y:
            if delta < 0:
                delta += (2 * x + 3)
            else:
                delta += (2 * (x - y) + 5)
                y -= 1
            x += 1
            self.paintPoints(x, y)
Exemplo n.º 34
0
 def __init__(self, img:QPixmap, parent=None):
     super().__init__(parent)
     self.img = img.scaled(50, 70)
     self.setPixmap(self.img)
Exemplo n.º 35
0
def msg_box_icon(msg, success: bool):
    if success:
        msg.setIconPixmap(QPixmap('assets/valid_big.png'))
    else:
        msg.setIconPixmap(QPixmap('assets/invalid_big.png'))
Exemplo n.º 36
0
 def showInputImageView(self):
     pixmap = QPixmap(self.inputImagePath).scaled(450, 300)
     self.inputImageView.setPixmap(pixmap)
     self.imageselected = True
Exemplo n.º 37
0
 def IconeFlorHome(self, botao, imagem):
     icon = QIcon()
     icon.addPixmap(QPixmap(imagem), QIcon.Normal, QIcon.Off)
     botao.setIcon(icon)
     botao.setIconSize(QSize(500, 300))
Exemplo n.º 38
0
class mainEditor(QWidget, Ui_mainEditor):
    """
    `mainEditor` is responsible for opening `outlineItem`s and offering information
    and commands about those `outlineItem`s to the used.

    It contains two main elements:

     1. A `tabSplitter`, which can open any number of `outlineItem`s either in tabs
        (in `QTabWidget`) and/or in split views (children `tabSplitter`s).
     2. An horizontal layout contain a number of buttons and information:

        - Go up button
        - Select folder view: either "text", "cork" or "outline" (see `editorWidget`)
        - Zoom slider for "cork" view
        - Label showing stats about displayed `outlineItem`
        - Fullscreen button

    `mainEditor` is responsible for opening indexes, propagating event to relevant
    views, opening and closing tabs, etc.

    +---------------------------| mainEditor |--------------------------------+
    |                                                                         |
    | +--------| tabSplitter |----------------------------------------------+ |
    | |                               +----------| tabSplitter |---------+  | |
    | |                               |                                  |  | |
    | |  +-----| editorWidget |----+  |  +-------| editorWidget |-----+  |  | |
    | |  |                         |  |  |                            |  |  | |
    | |  +-------------------------+  |  +----------------------------+  |  | |
    | |                               |                                  |  | |
    | |  +-----| editorWidget |----+  |  +-------| editorWidget |-----+  |  | |
    | |  |                         |  |  |                            |  |  | |
    | |  +-------------------------+  |  +----------------------------+  |  | |
    | |                               +----------------------------------+  | |
    | +---------------------------------------------------------------------+ |
    |                                                                         |
    +-------------------------------------------------------------------------+
    | ##  ##  ##  ##                toolbar                            ##  ## |
    +-------------------------------------------------------------------------+
    """
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setupUi(self)
        self._updating = False

        self.mw = mainWindow()

        # Connections --------------------------------------------------------

        self.btnGoUp.clicked.connect(self.goToParentItem)
        self.sldCorkSizeFactor.valueChanged.connect(self.setCorkSizeFactor,
                                                    AUC)
        self.btnRedacFolderCork.toggled.connect(
            self.sldCorkSizeFactor.setVisible, AUC)
        self.btnRedacFolderText.clicked.connect(
            lambda v: self.setFolderView("text"), AUC)
        self.btnRedacFolderCork.clicked.connect(
            lambda v: self.setFolderView("cork"), AUC)
        self.btnRedacFolderOutline.clicked.connect(
            lambda v: self.setFolderView("outline"), AUC)

        self.btnRedacFullscreen.clicked.connect(self.showFullScreen, AUC)

        # self.tab.setDocumentMode(False)

        # Bug in Qt < 5.5: doesn't always load icons from custom theme.
        # Cf. https://github.com/qtproject/qtbase/commit/a8621a3f85e64f1252a80ae81a6e22554f7b3f44
        # Since those are important, we provide fallback.
        self.btnRedacFolderCork.setIcon(
            QIcon.fromTheme(
                "view-cards",
                QIcon(
                    appPath("icons/NumixMsk/256x256/actions/view-cards.svg"))))
        self.btnRedacFolderOutline.setIcon(
            QIcon.fromTheme(
                "view-outline",
                QIcon(
                    appPath(
                        "icons/NumixMsk/256x256/actions/view-outline.svg"))))
        self.btnRedacFolderText.setIcon(
            QIcon.fromTheme(
                "view-text",
                QIcon(
                    appPath("icons/NumixMsk/256x256/actions/view-text.svg"))))

        for btn in [
                self.btnRedacFolderCork, self.btnRedacFolderText,
                self.btnRedacFolderOutline
        ]:
            btn.setToolTip(btn.text())
            btn.setText("")

    ###############################################################################
    # TABS
    ###############################################################################

    def currentTabWidget(self):
        """Returns the tabSplitter that has focus."""
        ts = self.tabSplitter
        while ts:
            if ts.focusTab == 1:
                return ts.tab
            else:
                ts = ts.secondTab

        # No tabSplitter has focus, something is strange.
        # But probably not important.
        # Let's return self.tabSplitter.tab anyway.
        return self.tabSplitter.tab

    def currentEditor(self, tabWidget=None):
        if tabWidget is None:
            tabWidget = self.currentTabWidget()
        return tabWidget.currentWidget()
        # return self.tab.currentWidget()

    def tabChanged(self, index=QModelIndex()):
        if self.currentEditor():
            index = self.currentEditor().currentIndex
            view = self.currentEditor().folderView
            self.updateFolderViewButtons(view)
        else:
            index = QModelIndex()

        self.updateMainTreeView(index)

        self.updateStats()
        self.updateThingsVisible(index)

    def updateMainTreeView(self, index):
        self._updating = True
        self.mw.treeRedacOutline.setCurrentIndex(index)
        self._updating = False

    def closeAllTabs(self):
        for ts in self.allTabSplitters():
            while (ts.tab.count()):
                ts.closeTab(0)

        for ts in reversed(self.allTabSplitters()):
            ts.closeSplit()

    def allTabs(self, tabWidget=None):
        """Returns all the tabs from the given tabWidget. If tabWidget is None, from the current tabWidget."""
        if tabWidget is None:
            tabWidget = self.currentTabWidget()
        return [tabWidget.widget(i) for i in range(tabWidget.count())]

    def allAllTabs(self):
        """Returns a list of all tabs, from all tabWidgets."""
        r = []
        for ts in self.allTabSplitters():
            r.extend(self.allTabs(ts.tab))
        return r

    def allTabSplitters(self):
        r = []
        ts = self.tabSplitter
        while ts:
            r.append(ts)
            ts = ts.secondTab
        return r

    ###############################################################################
    # SELECTION AND UPDATES
    ###############################################################################

    def selectionChanged(self):
        if self._updating:
            return

        # This might be called during a drag n drop operation, or while deleting
        # items. If so, we don't want to do anything.
        if not self.mw.mdlOutline._removingRows:
            if len(self.mw.treeRedacOutline.selectionModel().selection().
                   indexes()) == 0:
                idx = QModelIndex()
            else:
                idx = self.mw.treeRedacOutline.currentIndex()

            self.setCurrentModelIndex(idx)
            self.updateThingsVisible(idx)

    def openIndexes(self, indexes, newTab=False):
        for i in indexes:
            self.setCurrentModelIndex(i, newTab)

    def goToParentItem(self):
        if self.currentEditor():
            idx = self.currentEditor().currentIndex
            self.mw.treeRedacOutline.setCurrentIndex(idx.parent())

    def setCurrentModelIndex(self, index, newTab=False, tabWidget=None):

        title = self.getIndexTitle(index)

        if tabWidget is None:
            tabWidget = self.currentTabWidget()

        # Checking if tab is already opened
        for w in self.allTabs(tabWidget):
            if w.currentIndex == index:
                tabWidget.setCurrentWidget(w)
                return

        if qApp.keyboardModifiers() & Qt.ControlModifier:
            newTab = True

        if newTab or not tabWidget.count():
            editor = editorWidget(self)
            editor.setCurrentModelIndex(index)
            editor._tabWidget = tabWidget
            i = tabWidget.addTab(editor, editor.ellidedTitle(title))
            tabWidget.setTabToolTip(i, title)
            tabWidget.setCurrentIndex(tabWidget.count() - 1)
        else:
            self.currentEditor(tabWidget).setCurrentModelIndex(index)
            #tabWidget.setTabText(tabWidget.currentIndex(), title)

    def updateTargets(self):
        """Updates all tabSplitter that are targets. This is called from editorWidget."""
        index = self.sender().currentIndex()

        for ts in self.allTabSplitters():
            if ts.isTarget:
                self.updateMainTreeView(index)
                self.setCurrentModelIndex(index, tabWidget=ts.tab)
                self.updateThingsVisible(index)

    def getIndexTitle(self, index):
        if not index.isValid():
            title = self.tr("Root")
        else:
            title = index.internalPointer().title()

        return title

    ###############################################################################
    # FUNCTIONS FOR MENU ACCESS
    ###############################################################################

    def copy(self):
        self.currentEditor().copy()

    def cut(self):
        self.currentEditor().cut()

    def paste(self):
        self.currentEditor().paste()

    def rename(self):
        self.currentEditor().rename()

    def duplicate(self):
        self.currentEditor().duplicate()

    def delete(self):
        self.currentEditor().delete()

    def moveUp(self):
        self.currentEditor().moveUp()

    def moveDown(self):
        self.currentEditor().moveDown()

    def splitDialog(self):
        self.currentEditor().splitDialog()

    def splitCursor(self):
        self.currentEditor().splitCursor()

    def merge(self):
        self.currentEditor().merge()

    ###############################################################################
    # UI
    ###############################################################################

    def updateThingsVisible(self, index):
        if index.isValid():
            visible = index.internalPointer().isFolder()
        else:
            visible = True

        self.btnRedacFolderText.setVisible(visible)
        self.btnRedacFolderCork.setVisible(visible)
        self.btnRedacFolderOutline.setVisible(visible)
        self.sldCorkSizeFactor.setVisible(
            visible and self.btnRedacFolderCork.isChecked())
        self.btnRedacFullscreen.setVisible(not visible)

    def updateFolderViewButtons(self, view):
        if view == "text":
            self.btnRedacFolderText.setChecked(True)
        elif view == "cork":
            self.btnRedacFolderCork.setChecked(True)
        elif view == "outline":
            self.btnRedacFolderOutline.setChecked(True)

    def updateStats(self):

        if not self.currentEditor():
            return

        index = self.currentEditor().currentIndex
        if index.isValid():
            item = index.internalPointer()
        else:
            item = self.mw.mdlOutline.rootItem

        if not item:
            item = self.mw.mdlOutline.rootItem

        wc = item.data(Outline.wordCount)
        goal = item.data(Outline.goal)
        progress = item.data(Outline.goalPercentage)

        goal = uiParse(goal, None, int, lambda x: x >= 0)
        progress = uiParse(progress, 0.0, float)

        if not wc:
            wc = 0
        if goal:
            self.lblRedacProgress.show()
            rect = self.lblRedacProgress.geometry()
            rect = QRect(QPoint(0, 0), rect.size())
            self.px = QPixmap(rect.size())
            self.px.fill(Qt.transparent)
            p = QPainter(self.px)
            drawProgress(p, rect, progress, 2)
            del p
            self.lblRedacProgress.setPixmap(self.px)
            self.lblRedacWC.setText(
                self.tr("{} words / {} ").format(
                    locale.format_string("%d", wc, grouping=True),
                    locale.format_string("%d", goal, grouping=True)))
        else:
            self.lblRedacProgress.hide()
            self.lblRedacWC.setText(
                self.tr("{} words ").format(
                    locale.format_string("%d", wc, grouping=True)))

    ###############################################################################
    # VIEWS
    ###############################################################################

    def setFolderView(self, view):
        if self.currentEditor():
            self.currentEditor().setFolderView(view)

    def setCorkSizeFactor(self, val):
        for w in self.allAllTabs():
            w.setCorkSizeFactor(val)
        settings.corkSizeFactor = val

    def updateCorkView(self):
        for w in self.allAllTabs():
            w.corkView.viewport().update()

    def updateCorkBackground(self):
        for w in self.allAllTabs():
            w.corkView.updateBackground()

    def updateTreeView(self):
        for w in self.allAllTabs():
            w.outlineView.viewport().update()

    def showFullScreen(self):
        if self.currentEditor():
            self._fullScreen = fullScreenEditor(
                self.currentEditor().currentIndex)

    ###############################################################################
    # DICT AND STUFF LIKE THAT
    ###############################################################################

    def setDict(self, dict):
        print(dict)
        for w in self.allAllTabs():
            w.setDict(dict)

    def toggleSpellcheck(self, val):
        for w in self.allAllTabs():
            w.toggleSpellcheck(val)
Exemplo n.º 39
0
    def button_clicked(self, sending_button):
        if self.waitlist:
            try:
                old_root, manga_name, volume_name, label_name, jpg_name = self.waitlist[
                    0].split('/')
                self.current_img = self.waitlist[0]
                del self.waitlist[0]
                self.is_undo = True
            except:
                print('split errorqqqq')
        else:
            try:
                old_root, manga_name, volume_name, jpg_name = self.current_img.split(
                    '/')
            except:
                print('split erroreeee')

        middle = os.path.join(manga_name, volume_name)
        funcname = sending_button.text().lower()
        upped = funcname.upper()

        if funcname == 'shock/surprised':
            funcname = 'shock'

        elif funcname == 'delete':
            funcname = 'deformed'

        elif funcname == "don't know":
            funcname = 'pass'

        elif funcname == 'any of these':
            funcname = 'unclassified'

        item = QtWidgets.QListWidgetItem(f"{jpg_name} • {upped}")
        item.setIcon(QIcon(self.current_img))
        self.listWidget.insertItem(-1, item)

        img_new_path = os.path.join(self.new_root, middle, funcname, jpg_name)
        os.rename(self.current_img, img_new_path)

        if self.is_undo:
            pass
        else:
            self.jpg_count += 1

            if self.manga_count == len(self.mangas):
                print('ALL COMPLETED')
                return

            if len(self.mangas[self.manga_count].volumes[
                    self.volume_count].jpgs) == self.jpg_count:
                self.jpg_count = 0
                self.volume_count += 1

            if len(self.mangas[self.manga_count].volumes) == self.volume_count:
                self.jpg_count = 0
                self.manga_count += 1
        try:
            if self.waitlist:
                next_pic = self.waitlist[0]
            else:
                next_pic = self.mangas[self.manga_count].volumes[
                    self.volume_count].jpgs[self.jpg_count]

            self.current_img = next_pic
            if not self.waitlist:
                old_root, manga_name, volume_name, jpg_name = self.current_img.split(
                    '/')
                self.set_info_labels(manga_name, volume_name, jpg_name)
        except:
            print('YOUR FUNCTION IS ERRORIUS')
        pixmap = QPixmap(next_pic)
        self.img_label.setPixmap(pixmap)
        self.img_label.resize(150, 150)
        self.undo.append(img_new_path)
        self.is_undo = False
        print('new_path', img_new_path)
Exemplo n.º 40
0
    def setup_ui(self):
        """ Setup Ui
        """
        main_wrap = QVBoxLayout()
        main_wrap.setContentsMargins(0, 0, 0, 0)

        # updatebar on top
        self.update_bar = UpdateBar(self)
        self.update_bar.onUpdateNowClicked.connect(self._update_dwarf)
        self.update_bar.setVisible(False)
        main_wrap.addWidget(self.update_bar)

        # main content
        h_box = QHBoxLayout()
        h_box.setContentsMargins(15, 15, 15, 15)
        wrapper = QVBoxLayout()
        head = QHBoxLayout()
        head.setContentsMargins(50, 10, 0, 10)
        # dwarf icon
        icon = QLabel()
        icon.setPixmap(QPixmap(utils.resource_path('assets/dwarf.svg')))
        icon.setAlignment(Qt.AlignCenter)
        icon.setMinimumSize(QSize(125, 125))
        icon.setMaximumSize(QSize(125, 125))
        head.addWidget(icon)

        # main title
        v_box = QVBoxLayout()
        title = QLabel('Dwarf')
        title.setContentsMargins(0, 0, 0, 0)
        font = QFont('Anton', 100, QFont.Bold)
        font.setPixelSize(120)
        title.setFont(font)
        title.setMaximumHeight(125)
        title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        title.setAlignment(Qt.AlignCenter)
        head.addWidget(title)

        sub_title_text = (self._pick_random_word(0) + ' ' +
                          self._pick_random_word(1) + ' ' +
                          self._pick_random_word(2) + ' ' +
                          self._pick_random_word(3) + ' ' +
                          self._pick_random_word(4))
        sub_title_text = sub_title_text[:1].upper() + sub_title_text[1:]
        self._sub_title = QLabel(sub_title_text)
        font = QFont('OpenSans', 16, QFont.Bold)
        font.setPixelSize(24)
        self._sub_title.setFont(font)
        font_metric = QFontMetrics(self._sub_title.font())
        self._char_width = font_metric.widthChar('#')
        self._sub_title.setAlignment(Qt.AlignCenter)
        self._sub_title.setContentsMargins(175, 0, 0, 20)
        self._sub_title.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Minimum)
        v_box.addLayout(head)
        v_box.addWidget(self._sub_title)

        wrapper.addLayout(v_box)

        recent = QLabel('Recent saved Sessions')
        font = recent.font()
        font.setPixelSize(14)
        font.setBold(True)
        # font.setPointSize(10)
        recent.setFont(font)
        wrapper.addWidget(recent)
        wrapper.addWidget(self._recent_list)
        h_box.addLayout(wrapper, stretch=False)
        buttonSpacer = QSpacerItem(15, 100, QSizePolicy.Fixed,
                                   QSizePolicy.Minimum)
        h_box.addItem(buttonSpacer)
        wrapper = QVBoxLayout()

        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/android.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New Android Session')
        btn.clicked.connect(self._on_android_button)
        wrapper.addWidget(btn)

        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/apple.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New iOS Session')
        btn.clicked.connect(self._on_ios_button)
        wrapper.addWidget(btn)

        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/local.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New Local Session')
        btn.clicked.connect(self._on_local_button)
        wrapper.addWidget(btn)

        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/remote.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New Remote Session')
        btn.clicked.connect(self._on_remote_button)
        wrapper.addWidget(btn)

        h_box.addLayout(wrapper, stretch=False)
        main_wrap.addLayout(h_box)
        self.setLayout(main_wrap)
Exemplo n.º 41
0
 def IconeBotaoMenu(self, botao, imagem):
     icon = QIcon()
     icon.addPixmap(QPixmap(imagem),
                    QIcon.Normal, QIcon.Off)
     botao.setIcon(icon)
     botao.setIconSize(QSize(30, 30))
Exemplo n.º 42
0
	def keyPressEvent(self, e):
		if self.rob[0]!=3 and e.key() == 16777236:
			self.rob[0]+=1
			self.lbl[3][3].move(self.rob[0]*100, self.rob[1]*100)
			self.moveSound = "move.wav"
			QSound.play(self.moveSound)
			if self.rep==0:
				if self.rob[0]==a and self.rob[1]==b:
					self.lbl[2][2].setPixmap(QPixmap("empty.png"))
					self.lbl[2][2].move(a*100,b*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rep+=1
			if self.rop==0:
				if 	self.rob[0]==c and self.rob[1]==d:
					self.lbl[1][1].setPixmap(QPixmap("empty.png"))
					self.lbl[1][1].move(c*100,d*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rop+=1
		if self.rob[0]!=1 and e.key() == 16777234:
			self.rob[0]-=1
			self.lbl[3][3].move(self.rob[0]*100, self.rob[1]*100)
			self.moveSound = "move.wav"
			QSound.play(self.moveSound)
			if self.rep==0:
				if self.rob[0]==a and self.rob[1]==b:
					self.lbl[2][2].setPixmap(QPixmap("empty.png"))
					self.lbl[2][2].move(a*100,b*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rep+=1
			if self.rop==0:
				if 	self.rob[0]==c and self.rob[1]==d:
					self.lbl[1][1].setPixmap(QPixmap("empty.png"))
					self.lbl[1][1].move(c*100,d*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rop+=1
		if self.rob[1]!=1 and e.key() == 16777235:
			self.rob[1]-=1
			self.lbl[3][3].move(self.rob[0]*100, self.rob[1]*100)	
			self.moveSound = "move.wav"
			QSound.play(self.moveSound)
			if self.rep==0:
				if self.rob[0]==a and self.rob[1]==b:
					self.lbl[2][2].setPixmap(QPixmap("empty.png"))
					self.lbl[2][2].move(a*100,b*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rep+=1
			if self.rop==0:
				if 	self.rob[0]==c and self.rob[1]==d:
					self.lbl[1][1].setPixmap(QPixmap("empty.png"))
					self.lbl[1][1].move(c*100,d*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rop+=1
		if self.rob[1]!=3 and e.key() == 16777237:
			self.rob[1]+=1
			self.lbl[3][3].move(self.rob[0]*100, self.rob[1]*100)
			self.moveSound = "move.wav"
			QSound.play(self.moveSound)
			if self.rep==0:
				if self.rob[0]==a and self.rob[1]==b:
					self.lbl[2][2].setPixmap(QPixmap("empty.png"))
					self.lbl[2][2].move(a*100,b*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rep+=1
			if self.rop==0:
				if 	self.rob[0]==c and self.rob[1]==d:
					self.lbl[1][1].setPixmap(QPixmap("empty.png"))
					self.lbl[1][1].move(c*100,d*100)
					self.moveSound = "gold.wav"
					QSound.play(self.moveSound)
					self.rop+=1
Exemplo n.º 43
0
class Pycomics(QMainWindow):

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

        self.InitActions()
        self.InitConfig()
        self.InitDialog()
        self.InitMenu()
        self.InitToolbar()
        self.InitStatusbar()
        self.InitUI()

    def showEvent(self,event):
        pass

    def closeEvent(self,event):
        self.SaveConfig()

    def resizeEvent(self,event):
        self.ResizeViewer()

    def InitConfig(self):
        config = configparser.ConfigParser()
        config.read('pycomics.ini')
        
        self.path = config.get('DEFAULT','path',fallback='')
        self.folder = config.get('DEFAULT','folder',fallback='')
        self.SortOrder = config.getint('DEFAULT','sortorder',fallback=0)
        self.SortAlg = config.getint('DEFAULT','sortalg',fallback=0)
        self.ALastScene.setChecked(config.getboolean('DEFAULT','lastscene',fallback=False))
        self.AOriSize.setChecked(config.getboolean('DEFAULT','orisize',fallback=False))
        self.AFitScreen.setChecked(config.getboolean('DEFAULT','fitscreen',fallback=False))
        self.AFitHeight.setChecked(config.getboolean('DEFAULT','fitheight',fallback=False))
        self.AFitWidth.setChecked(config.getboolean('DEFAULT','fitwidth',fallback=False))
        self.IsArchive = config.getboolean('DEFAULT','isarchive',fallback=False)
        self.IndexInArchive = config.getint('DEFAULT','archiveindex',fallback=0)
        self.initx = config.getint('DEFAULT','x',fallback=50) 
        self.inity = config.getint('DEFAULT','y',fallback=50) 
        self.initheight = config.getint('DEFAULT','height',fallback = 600) or 600
        self.initwidth = config.getint('DEFAULT','width',fallback = 800) or 800
        self.initwindowstate = config.getint('DEFAULT','windowstate',fallback=0)

    def SaveConfig(self):
        config = configparser.ConfigParser()
        config.read('pycomics.ini')
        window_state = str(int(self.windowState()))
        config.set('DEFAULT','path',self.path)
        config.set('DEFAULT','folder',self.folder)
        config.set('DEFAULT','sortorder',str(self.SortOrder))
        config.set('DEFAULT','sortalg',str(self.SortAlg))
        config.set('DEFAULT','lastscene', str(self.ALastScene.isChecked()))
        config.set('DEFAULT','isarchive', str(self.IsArchive))
        config.set('DEFAULT','archiveindex', str(self.IndexInArchive))
        config.set('DEFAULT','orisize', str(self.AOriSize.isChecked()))
        config.set('DEFAULT','fitscreen', str(self.AFitScreen.isChecked()))
        config.set('DEFAULT','fitheight', str(self.AFitHeight.isChecked()))
        config.set('DEFAULT','fitwidth', str(self.AFitWidth.isChecked()))
        config.set('DEFAULT','windowstate',window_state)
        if window_state == '0':
            config.set('DEFAULT','x',str(self.geometry().x()))
            config.set('DEFAULT','y',str(self.geometry().y()))
            config.set('DEFAULT','height',str(self.geometry().height()))
            config.set('DEFAULT','width',str(self.geometry().width()))

        with open('pycomics.ini','w') as configfile:
            config.write(configfile)

    def InitDialog(self):
        self.PwdDialog = pwdmgr.PwdManager()
        self.ListDialog = listmgr.ListManager()
        self.ListDialog.SortOrder[self.SortOrder].click()
        self.ListDialog.SortAlg[self.SortAlg].click()

    def InitUI(self):
        self.ImageViewer = QLabel()
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidget(self.ImageViewer)
        self.setCentralWidget(self.scrollArea)
        self.scrollArea.setAlignment(Qt.AlignCenter)
        self.setWindowTitle(__Title__ + ' ' + __Version__)
        self.setGeometry(self.initx,self.inity ,self.initwidth,self.initheight)
        self.AllFiles = []
        self.show()
        if self.initwindowstate == 1:
            self.setWindowState(Qt.WindowMinimized)
        elif self.initwindowstate == 2:
            self.setWindowState(Qt.WindowMaximized)
        elif self.initwindowstate == 3:
            self.setWindowState(Qt.WindowMaximized)
            self.setWindowState(Qt.WindowMinimized)

    def InitActions(self):
        self.AExit = QAction(QIcon('icon' + os.sep + 'logout.png'), 'Exit', self)
        self.AExit.setShortcut('ESC')
        self.AExit.setStatusTip('Exit application')
        self.AExit.triggered.connect(self.close)

        self.AOpen = QAction(QIcon('icon' + os.sep + 'file.png'), 'Open Files', self)
        self.AOpen .setShortcut('Ctrl+O')
        self.AOpen .setStatusTip('Open Files')
        self.AOpen .triggered.connect(self.OpenFile)

        self.AOpenFolder = QAction(QIcon('icon' + os.sep + 'file.png'), 'Open Folder', self)
        self.AOpenFolder .setShortcut('Ctrl+O')
        self.AOpenFolder .setStatusTip('Open Folder')
        self.AOpenFolder .triggered.connect(self.OpenFolder)

        self.APrev = QAction(QIcon('icon' + os.sep + 'file.png'), 'PreviousPage', self)
        self.APrev .setShortcut('Left')
        self.APrev .setStatusTip('PreviousPage')
        self.APrev .triggered.connect(self.PrevPage)

        self.ANext = QAction(QIcon('icon' + os.sep + 'file.png'), 'NextPage', self)
        self.ANext .setShortcut('Right')
        self.ANext .setStatusTip('NextPage')
        self.ANext .triggered.connect(self.NextPage)

        self.AFirst = QAction(QIcon('icon' + os.sep + 'file.png'), 'FirstPage', self)
        self.AFirst .setShortcut('home')
        self.AFirst .setStatusTip('FirstPage')
        self.AFirst .triggered.connect(self.FirstPage)

        self.ALast = QAction(QIcon('icon' + os.sep + 'file.png'), 'LastPage', self)
        self.ALast .setShortcut('end')
        self.ALast .setStatusTip('LastPage')
        self.ALast .triggered.connect(self.LastPage)

        self.ALastScene = QAction(QIcon('icon' + os.sep + 'file.png'),'Last Scene',self,checkable=True)
        self.ALastScene .setCheckable = True
        self.ALastScene .setStatusTip('LastScene')

        self.AOriSize = QAction(QIcon('icon' + os.sep + 'file.png'),'Original Size',self,checkable=True)
        self.AOriSize .setCheckable = True
        self.AOriSize .setStatusTip('Original Size')

        self.AFitScreen = QAction(QIcon('icon' + os.sep + 'file.png'),'Fit Screen',self,checkable=True)
        self.AFitScreen .setCheckable = True
        self.AFitScreen .setStatusTip('FitScreen')

        self.AFitHeight = QAction(QIcon('icon' + os.sep + 'file.png'),'Fit Height',self,checkable=True)
        self.AFitHeight .setCheckable = True
        self.AFitHeight .setStatusTip('FitHeight')

        self.AFitWidth = QAction(QIcon('icon' + os.sep + 'file.png'),'Fit Width',self,checkable=True)
        self.AFitWidth .setCheckable = True
        self.AFitWidth .setStatusTip('FitWidth')

        self.AFitGroup = QActionGroup(self)
        self.AFitGroup.addAction(self.AOriSize)
        self.AFitGroup.addAction(self.AFitScreen)
        self.AFitGroup.addAction(self.AFitHeight)
        self.AFitGroup.addAction(self.AFitWidth)
        self.AOriSize.setChecked(True)
        self.AFitGroup.triggered.connect(self.ResizeViewer)

        self.APwdManager = QAction(QIcon('icon' + os.sep + 'file.png'), 'Password Manager', self)
        self.APwdManager .setStatusTip('Password Manager')
        self.APwdManager .triggered.connect(self.ShowPwdManager)

        self.AListManager = QAction(QIcon('icon' + os.sep + 'file.png'), 'List Manager', self)
        self.AListManager .setStatusTip('List Manager')
        self.AListManager .triggered.connect(self.ShowListManager)

    def InitMenu(self):
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(self.AOpen)
        fileMenu.addAction(self.AOpenFolder)
        fileMenu.addAction(self.AExit)

        fileMenu = menubar.addMenu('&View')
        fileMenu.addAction(self.AFirst)
        fileMenu.addAction(self.APrev)
        fileMenu.addAction(self.ANext)
        fileMenu.addAction(self.ALast)

        fileMenu = menubar.addMenu('&Settings')
        fileMenu.addAction(self.APwdManager)
        fileMenu.addAction(self.ALastScene)

    def InitToolbar(self):
        self.toolBar = self.addToolBar('Toolbar')
        self.toolBar.setMovable(False)
        self.toolBar.addAction(self.AOpen)
        self.toolBar.addAction(self.AOpenFolder)
        self.toolBar.addAction(self.AListManager)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.AFirst)
        self.toolBar.addAction(self.APrev)
        self.toolBar.addAction(self.ANext)
        self.toolBar.addAction(self.ALast)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.AOriSize)
        self.toolBar.addAction(self.AFitScreen)
        self.toolBar.addAction(self.AFitHeight)
        self.toolBar.addAction(self.AFitWidth)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.ALastScene)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.AExit)

    def InitStatusbar(self): 
        statusbar = self.statusBar()
        self.StatusPath = QLabel()
        self.StatusFilename = QLabel()
        self.StatusIndex = QLabel()
        self.StatusSize = QLabel()
        statusbar.addWidget(self.StatusPath)
        statusbar.addPermanentWidget(self.StatusFilename)
        statusbar.addPermanentWidget(self.StatusIndex)
        statusbar.addPermanentWidget(self.StatusSize)

    def InitLastScene(self):
        if self.ALastScene.isChecked() and self.path:
            self.LoadFile(self.path)

    def ShowOpenFileDialog(self):
        path = QFileDialog.getOpenFileName(self, 'Open File','', 'Support Files (*.png *.jpeg *.jpg *.bmp *.zip *.rar *.7z);;Images (*.png *.jpeg *.jpg *.bmp);;Zip (*.zip)')
        if path[0]:
            return os.path.realpath(path[0])

    def ShowOpenFolderDialog(self):
        path = QFileDialog.getExistingDirectory(self, 'Open Folder','', QFileDialog.ShowDirsOnly)
        if path:
            return os.path.realpath(path)

    def OpenFile(self):
        filepath = self.ShowOpenFileDialog()
        if filepath:
            self.folderpath = ''
            self.CloseArchive()
            self.LoadFile(filepath)

    def OpenFolder(self):
        folder = self.ShowOpenFolderDialog()
        if folder:
            self.folderpath = folder
            self.CloseArchive()
            self.LoadFile(folder)

    def LoadFile(self,path):
        if os.path.isdir(path):
            folder = path
            fname = ''
        elif os.path.isfile(path):
            folder,fname = os.path.split(path)
        else:
            self.LoadFailed()
            return
        if self.folder:
            if not os.path.isdir(self.folder):
                self.folder = folder
            self.AllFiles = self.GetAllFiles(self.folder)
        else:
            self.AllFiles = self.GetAllFiles(folder)
        if len(self.AllFiles) == 0:
            return
        if fname:
            self.fileindex = self.AllFiles.index(path)
        else:
            self.fileindex = 0
            path = self.AllFiles[0]
            fname = os.path.basename(path)
        self.path = path
        self.IsArchive,self.ext = self.IsCompressed(path)
        if self.IsArchive:
            if self.ext == '.zip':
                self.ArchiveFile = zipfile.ZipFile(path, 'r')
                AcrhiveFileList = self.ArchiveFile.namelist()
                self.ArchiveInfo = self.ArchiveFile.infolist()
                self.IsEncrypted = self.ArchiveInfo[0].flag_bits & 0x1 
                if self.IsEncrypted:
                    self.Pass,self.Pwd = self.DecryptArchive(self.ArchiveFile)
                    if self.Pass:
                        pass
                    else:
                        self.LoadFailed()
                        return
                else: 
                    self.Pwd = None
                self.AllFilesInArchive = self.GetAllFilesInArchive(AcrhiveFileList)
                self.ShowImage()
            elif self.ext == '.rar':
                self.ArchiveFile = rarfile.RarFile(path, 'r')
                AcrhiveFileList = self.ArchiveFile.namelist()
                self.ArchiveInfo = self.ArchiveFile.infolist()
                self.IsEncrypted = self.ArchiveInfo[0].needs_password()
                if self.IsEncrypted:
                    self.Pass,self.Pwd = self.DecryptArchive(self.ArchiveFile)
                    if self.Pass:
                        pass
                    else:
                        self.LoadFailed()
                        return
                else: 
                    self.Pwd = None
                self.AllFilesInArchive = self.GetAllFilesInArchive(AcrhiveFileList)
                self.ShowImage()
            elif self.ext == '.7z':
                self.Pass = False
                self.LoadFailed()
            else:
                self.Pass = False
                self.LoadFailed()
        else:
            self.IndexInArchive = 0
            self.ShowImage()

    def ShowImage(self):
        if self.IsArchive:
            fname = self.AllFilesInArchive[self.IndexInArchive]
            data =self.ArchiveFile.read(fname,self.Pwd)
            self.pixmap = QPixmap.fromImage(QImage.fromData(data))
        else:
            fname = self.AllFiles[self.fileindex]
            self.pixmap = QPixmap(fname)

        if self.pixmap.isNull():
            self.LoadFailed()
            self.UpdateStatus()
        else:
            self.ImageViewer.setPixmap(self.pixmap)
            self.UpdateStatus()
            self.ResizeViewer()

    def UpdateStatus(self):
        if self.IsArchive:
            fname = self.AllFilesInArchive[self.IndexInArchive]
            self.StatusPath.setText(self.AllFiles[self.fileindex])
            self.StatusFilename.setText(fname)
            self.StatusIndex.setText(str(self.IndexInArchive+1) + '/' + str(len(self.AllFilesInArchive)))
        else:
            fname = self.AllFiles[self.fileindex]
            self.StatusPath.setText(fname)
            self.StatusFilename.setText(os.path.split(fname)[1])
            self.StatusIndex.setText(str(self.fileindex+1) + '/' + str(len(self.AllFiles)))

        try:
            h = str(self.pixmap.height())
            w = str(self.pixmap.width())
            self.StatusSize.setText(w + '*' + h)
        except:
            pass

    def ResizeViewer(self):
        try:
            if self.AOriSize.isChecked():
                scale = 1
            else:
                viewh = self.height() - self.menuBar().height() - self.toolBar.height() - self.statusBar().height() -2
                vieww = self.width() -2
                hscale=viewh/self.pixmap.height()
                wscale=vieww/self.pixmap.width()
                if self.AFitScreen.isChecked():
                    scale = min(hscale,wscale)
                elif self.AFitWidth.isChecked():
                    scale = wscale
                elif self.AFitHeight.isChecked():
                    scale = hscale
                else:
                    scale = 1

            self.ImageViewer.resize(self.pixmap.width()*scale,self.pixmap.height()*scale)
            self.ImageViewer.setScaledContents(True)
            self.pixmap.scaled(self.ImageViewer.size(),Qt.KeepAspectRatio, transformMode = Qt.SmoothTransformation)
            self.ImageViewer.setAlignment(Qt.AlignCenter)
        except:
            pass

    def SupportFile(self,fname):
        supportext =['.jpg','.png','.jpeg','.bmp','.zip','.rar','.7z']
        ext = os.path.splitext(fname)[1]
        if ext in supportext:
            return True
        else:
            return False
    
    def SupportFileInArchive(self,fname):
        supportext =['.jpg','.png','.jpeg','.bmp']
        ext = os.path.splitext(fname)[1]
        if ext in supportext:
            return True
        else:
            return False

    def IsCompressed(self,fname):
        compressed =['.zip','.rar','.7z']
        ext = os.path.splitext(fname)[1]
        if ext in compressed:
            return True,ext
        else:
            return False,ext

    def GetAllFiles(self,folder):
        file_paths = []
        for root, directories, files in os.walk(folder):
            for filename in files:
                filepath = os.path.join(root, filename)
                if self.SupportFile(filepath):
                    file_paths.append(filepath)
        file_paths = self.ListDialog.Sort(file_paths,self.SortOrder,self.SortAlg)
        return file_paths

    def GetAllFilesInArchive(self,namelist):
        support_file = []
        for files in namelist:
                if self.SupportFileInArchive(files):
                    support_file.append(files)
        file_paths = self.ListDialog.Sort(support_file,self.SortOrder,self.SortAlg)
        return file_paths

    def PrevPage(self):
        if self.IsArchive:
            if self.IndexInArchive>0:
                self.IndexInArchive -=1
                self.ShowImage()
            else:
                if self.fileindex>0:
                    self.CloseArchive()
                    self.fileindex -=1
                    self.LoadFile(self.AllFiles[self.fileindex])
        else:
            if self.fileindex>0:
                self.fileindex -=1
                self.LoadFile(self.AllFiles[self.fileindex])

    def NextPage(self):
        if self.IsArchive:
            if self.IndexInArchive < len(self.AllFilesInArchive)-1:
                self.IndexInArchive +=1
                self.ShowImage()
            else:
                if self.fileindex < len(self.AllFiles)-1:
                    self.CloseArchive()
                    self.fileindex +=1
                    self.LoadFile(self.AllFiles[self.fileindex])
        else:
            if self.fileindex < len(self.AllFiles)-1:
                self.fileindex +=1
                self.LoadFile(self.AllFiles[self.fileindex])

    def FirstPage(self):
        if self.IsArchive:
            self.IndexInArchive = 0
            self.ShowImage()
        else:
            self.fileindex = 0
            self.LoadFile(self.AllFiles[self.fileindex])

    def LastPage(self):
        if self.IsArchive:
            self.IndexInArchive = len(self.AllFilesInArchive)-1
            self.ShowImage()
        else:
            self.fileindex = len(self.AllFiles)-1
            self.LoadFile(self.AllFiles[self.fileindex])

    def LoadPwd(self):
        if not os.path.exists(r'password.pwd'):
            open("password.pwd","wb").close()
        if self.ext == '.zip':
            pwdf = open('password.pwd','rb')
        else:
            pwdf = open('password.pwd','r')
        self.PwdList = pwdf.read().splitlines()
        pwdf.close()

    def DecryptArchive(self,archivefile):
        self.LoadPwd()
        self.IsPwdChanged = True
        IsPwdFound = False
        while self.IsPwdChanged and not IsPwdFound:
            for password in self.PwdList:
                try:
                    data = self.ArchiveFile.read(self.ArchiveInfo[0].filename,password)
                    IsPwdFound = True
                    return IsPwdFound,password
                except:
                    pass
            self.ShowPwdManager()
        return IsPwdFound,None

    def LoadFailed(self):
        if self.IsArchive and not self.Pass:
            self.IsArchive = False

        self.UpdateStatus()

        self.ImageViewer.setText("Can not load %s" % self.StatusFilename.text())
        self.ImageViewer.resize(300,50)
        self.ImageViewer.setAlignment(Qt.AlignCenter)

    def ShowPwdManager(self):
        if self.PwdDialog.exec_():
            self.IsPwdChanged = True
            self.LoadPwd()
        else:
            self.IsPwdChanged = False

    def ShowListManager(self):
        if self.IsArchive:
            self.ListDialog.list = self.AllFilesInArchive
            self.ListDialog.path = self.AllFilesInArchive[self.IndexInArchive]
        else:
            self.ListDialog.list = self.AllFiles
            self.ListDialog.path = self.path
        if self.ListDialog.exec_():
            self.SortOrder = self.ListDialog.OrderGroup.checkedId()
            self.SortAlg = self.ListDialog.AlgGroup.checkedId()
            if self.IsArchive:
                self.ListDialog.Sort(self.AllFilesInArchive,self.SortOrder,self.SortAlg)
                self.IndexInArchive = self.ListDialog.index
                self.ShowImage()
            else:
                if self.AllFiles:
                    self.LoadFile(self.ListDialog.path)

    def CloseArchive(self):
        self.IndexInArchive = 0
        try:
            self.ArchiveFile.close()
        except AttributeError:
            pass
Exemplo n.º 44
0
    def interfejs(self, user):
        # CSS

        stylesheet = '''
                        QWidget{
                            
                        }
                        QPushButton{
                            background-color:#8ceda6;
                            border-color: #8ceda6;
                            color: #222;
                            font-weight:bold;
                            font-family:Arial;
                            font-size:16px;
                            width:100%;
                            height: 25%;
                        }
                        QPushButton:hover{
                            background-color:#8ceda6;
                            color:white;
                        }
                        QPushButton#disabled{
                            background-color:#999;
                            color:white;
                        }


                        QLabel{
                            font-size:20px;
                        }
            '''
        # widgety
        cur.execute("USE project")
        cur.execute("SELECT image FROM users WHERE login='******'".format(user))
        query = cur.fetchall()
        for rekord in query:
            zdj = "user.png"

        if zdj == False:
            zdj = 'user.png'
        ukladT = QGridLayout()
        photo = QLabel(self)
        pixmap = QPixmap(zdj)
        pixmap = pixmap.scaled(170, 220)
        photo.setPixmap(pixmap)
        self.hello = QLabel("Hello, <b>{}</b>".format(user), self)
        addPhotoBtn = QPushButton("Update your photo", self)
        show_dataBtn = QPushButton("&Show My Data", self)
        edit_dataBtn = QPushButton("&Edit My Data", self)
        show_all_usersBtn = QPushButton("&Show all users", self)
        deleteBtn = QPushButton("&Delete My Account", self)
        backBtn = QPushButton("&Log out", self)

        show_dataBtn.resize(show_dataBtn.sizeHint())
        edit_dataBtn.resize(edit_dataBtn.sizeHint())
        show_all_usersBtn.resize(show_all_usersBtn.sizeHint())
        deleteBtn.resize(deleteBtn.sizeHint())
        backBtn.resize(backBtn.sizeHint())

        ukladT.addWidget(self.hello, 0, 0, 1, 2)
        ukladT.addWidget(addPhotoBtn, 1, 0, 1, 3)
        ukladT.addWidget(photo, 0, 3)
        ukladT.addWidget(show_dataBtn, 2, 0, 1, 4)
        ukladT.addWidget(edit_dataBtn, 3, 0, 1, 4)
        ukladT.addWidget(show_all_usersBtn, 4, 0, 1, 4)
        ukladT.addWidget(deleteBtn, 5, 0, 1, 4)
        ukladT.addWidget(backBtn, 6, 0, 1, 4)
        self.setLayout(ukladT)
        self.setFixedWidth(400)
        self.setFixedHeight(500)

        backBtn.clicked.connect(self.back)
        addPhotoBtn.clicked.connect(self.choose_photo)
        show_dataBtn.clicked.connect(self.show_data)
        edit_dataBtn.clicked.connect(self.edit_data)
        deleteBtn.clicked.connect(self.deleteAccount)
        if self.user != 'Admin':
            show_all_usersBtn.setObjectName("disabled")
            show_all_usersBtn.setDisabled(True)
            show_all_usersBtn.setToolTip("For Admin only")
        else:
            show_all_usersBtn.clicked.connect(self.show_all)

        self.setWindowTitle("Logging system")
        self.setWindowIcon(QIcon('img/user.png'))
        self.setStyleSheet(stylesheet)
        self.show()
Exemplo n.º 45
0
    def createCurveIcons(self):
        pix = QPixmap(self.m_iconSize)
        painter = QPainter()

        gradient = QLinearGradient(0, 0, 0, self.m_iconSize.height())
        gradient.setColorAt(0.0, QColor(240, 240, 240))
        gradient.setColorAt(1.0, QColor(224, 224, 224))

        brush = QBrush(gradient)

        # The original C++ code uses undocumented calls to get the names of the
        # different curve types.  We do the Python equivalant (but without
        # cheating).
        curve_types = [
            (n, c) for n, c in QEasingCurve.__dict__.items()
            if isinstance(c, QEasingCurve.Type) and c != QEasingCurve.Custom
        ]
        curve_types.sort(key=lambda ct: ct[1])

        painter.begin(pix)

        for curve_name, curve_type in curve_types:
            painter.fillRect(QRect(QPoint(0, 0), self.m_iconSize), brush)

            curve = QEasingCurve(curve_type)

            if curve_type == QEasingCurve.BezierSpline:
                curve.addCubicBezierSegment(QPointF(0.4,
                                                    0.1), QPointF(0.6, 0.9),
                                            QPointF(1.0, 1.0))
            elif curve_type == QEasingCurve.TCBSpline:
                curve.addTCBSegment(QPointF(0.0, 0.0), 0, 0, 0)
                curve.addTCBSegment(QPointF(0.3, 0.4), 0.2, 1, -0.2)
                curve.addTCBSegment(QPointF(0.7, 0.6), -0.2, 1, 0.2)
                curve.addTCBSegment(QPointF(1.0, 1.0), 0, 0, 0)

            painter.setPen(QColor(0, 0, 255, 64))
            xAxis = self.m_iconSize.height() / 1.5
            yAxis = self.m_iconSize.width() / 3.0
            painter.drawLine(0, xAxis, self.m_iconSize.width(), xAxis)
            painter.drawLine(yAxis, 0, yAxis, self.m_iconSize.height())

            curveScale = self.m_iconSize.height() / 2.0

            painter.setPen(Qt.NoPen)

            # Start point.
            painter.setBrush(Qt.red)
            start = QPoint(yAxis,
                           xAxis - curveScale * curve.valueForProgress(0))
            painter.drawRect(start.x() - 1, start.y() - 1, 3, 3)

            # End point.
            painter.setBrush(Qt.blue)
            end = QPoint(yAxis + curveScale,
                         xAxis - curveScale * curve.valueForProgress(1))
            painter.drawRect(end.x() - 1, end.y() - 1, 3, 3)

            curvePath = QPainterPath()
            curvePath.moveTo(QPointF(start))
            t = 0.0
            while t <= 1.0:
                to = QPointF(yAxis + curveScale * t,
                             xAxis - curveScale * curve.valueForProgress(t))
                curvePath.lineTo(to)
                t += 1.0 / curveScale

            painter.setRenderHint(QPainter.Antialiasing, True)
            painter.strokePath(curvePath, QColor(32, 32, 32))
            painter.setRenderHint(QPainter.Antialiasing, False)

            item = QListWidgetItem()
            item.setIcon(QIcon(pix))
            item.setText(curve_name)
            self.m_ui.easingCurvePicker.addItem(item)

        painter.end()
Exemplo n.º 46
0

class View(QGraphicsView):
    def resizeEvent(self, event):
        super(View, self).resizeEvent(event)
        self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)


if __name__ == '__main__':

    import sys
    import math

    app = QApplication(sys.argv)

    kineticPix = QPixmap(':/images/kinetic.png')
    bgPix = QPixmap(':/images/Time-For-Lunch-2.jpg')

    scene = QGraphicsScene(-350, -350, 700, 700)

    items = []
    for i in range(64):
        item = Pixmap(kineticPix)
        item.pixmap_item.setOffset(-kineticPix.width() / 2,
                                   -kineticPix.height() / 2)
        item.pixmap_item.setZValue(i)
        items.append(item)
        scene.addItem(item.pixmap_item)

    # Buttons.
    buttonParent = QGraphicsRectItem()
Exemplo n.º 47
0
    def _uic(self):
        '''
    set up our layout which consists of:

                 Big Honkin' Label
        [input combobox]    [output combobox]
               [volume slider]  [x] Mute

    Hooking the signals to useful slots is the job
    of __init__. Here just make the layout.
        '''
        self.setMinimumWidth(400)
        # Create the big honkin' label and logo
        icon_pixmap = QPixmap(':/icon.png').scaledToWidth(64)
        icon_label = QLabel()
        icon_label.setPixmap(icon_pixmap)
        text_label = QLabel("Sidetone!")
        hb_label = QHBoxLayout()
        hb_label.addStretch(1)
        hb_label.addWidget(icon_label, 0)
        hb_label.addWidget(text_label, 0)
        hb_label.addStretch(1)

        # Create a list of QAudioInfo objects for inputs
        self.input_info_list = QAudioDeviceInfo.availableDevices(
            QAudio.AudioInput)
        if 0 == len(self.input_info_list):
            self.input_info_list = [QAudioDeviceInfo.defaultInputDevice()]
        # Make a list of the name-strings for those items.
        in_dev_names = [
            audio_info.deviceName() for audio_info in self.input_info_list
        ]
        # Create a combo box and populate it with those names
        self.cb_inputs = QComboBox()
        self.cb_inputs.addItems(in_dev_names)
        # If the in_dev_name from the previous run is in the current list,
        # make it current, otherwise pick the first item.
        in_dev_name = self.settings.value('in_dev_name', 'unknown')
        if in_dev_name in in_dev_names:
            self.cb_inputs.setCurrentIndex(in_dev_names.index(in_dev_name))
        else:
            self.cb_inputs.setCurrentIndex(0)

        # Create a list of QAudioInfo objects for outputs
        self.otput_info_list = QAudioDeviceInfo.availableDevices(
            QAudio.AudioOutput)
        if 0 == len(self.otput_info_list):
            self.otput_info_list = [QAudioDeviceInfo.defaultOutputDevice()]
        # Make a list of the name-strings of those things
        ot_dev_names = [
            audio_info.deviceName() for audio_info in self.otput_info_list
        ]
        # Create a combo box and populate it with those names
        self.cb_otputs = QComboBox()
        self.cb_otputs.addItems(ot_dev_names)
        # If the ot_dev_name from the previous run is in the current list,
        # make it the current choice in the box.
        ot_dev_name = self.settings.value('ot_dev_name', 'unknown')
        if ot_dev_name in ot_dev_names:
            self.cb_otputs.setCurrentIndex(ot_dev_names.index(ot_dev_name))
        else:
            self.cb_otputs.setCurrentIndex(0)

        #self.show_status(
        #'{} inputs {} otputs'.format(len(self.input_info_list),len(self.otput_info_list))
        #)
        # Create a combo box and populate it with names of outputs

        # Lay those two out aligned to the outside
        hb_combos = QHBoxLayout()
        hb_combos.addWidget(self.cb_inputs, 1)
        hb_combos.addStretch(0)
        hb_combos.addWidget(self.cb_otputs, 1)

        # Create a volume slider from 0 to 100.
        self.volume = QSlider(Qt.Horizontal, self)
        self.volume.setMinimum(0)
        self.volume.setMaximum(100)
        self.volume.setTickInterval(10)
        self.volume.setTickPosition(QSlider.TicksBothSides)
        # set the volume slider to the value from the previous run, or zero.
        self.volume.setValue(self.settings.value('volume', 0))

        # Create a checkbox "Mute"
        self.mute = QCheckBox('Mute')
        # Set it to the value at the end of the last run, or to True
        self.mute.setChecked(bool(self.settings.value('mute_status', 1)))

        # Put those together in a row squeezed in the center
        hb_volume = QHBoxLayout()
        hb_volume.addStretch(1)
        hb_volume.addWidget(self.volume, 1)
        hb_volume.addWidget(self.mute, 0)
        hb_volume.addStretch(1)

        # Stack all those up as this widget's layout
        vlayout = QVBoxLayout()
        vlayout.addLayout(hb_label)
        vlayout.addLayout(hb_combos)
        vlayout.addLayout(hb_volume)
        self.setLayout(vlayout)
Exemplo n.º 48
0
 def preview_mask(self):
     self.new_mask_image = self.create_mask(self.control_image,
                                            self.rendered_image,
                                            self.mask_image,
                                            self.overload_spin.value())
     self.new_mask_label.setPixmap(QPixmap.fromImage(self.new_mask_image))
Exemplo n.º 49
0
    def show_act_val(self, manual=False):
        self.show_all_activation()

        if not self.data_loaded:
            self.gfc_data = pd.read_excel(default_gfc_data_excel_path)
            self.data_loaded = True

        if manual:
            from_time = self.from_time.dateTime().toString(Qt.ISODate).replace(
                "T", " ")
            to_time = self.to_time.dateTime().toString(Qt.ISODate).replace(
                "T", " ")

            self.from_time_stamp.setText(":".join(
                from_time.split(" ")[1].split(":")[:2]))
            to_time_stamp = ":".join(to_time.split(" ")[1].split(":")[:2])
            if to_time_stamp == "00:00":
                to_time_stamp = "24:00"
            self.to_time_stamp.setText(to_time_stamp)

            ans = cal_act(
                self.gfc_data,
                from_time,
                to_time,
                category=self.config,
                mac_type=self.mac_type,
                output="%s%s_%s.csv" %
                (default_output_csv_path, self.config, self.mac_type))
            if ans:
                yield_vals, act_vals, act_pics, osfrs, global_osfr, global_yield = ans
            else:
                return False
        else:
            self.gfc_data = pd.read_excel(default_gfc_data_excel_path)
            ans = cal_act(
                self.gfc_data,
                category=self.config,
                mac_type=self.mac_type,
                output="%s%s_%s.csv" %
                (default_output_csv_path, self.config, self.mac_type))
            if ans:
                yield_vals, act_vals, act_pics, osfrs, global_osfr, global_yield = ans
            else:
                return False
        self.active_labels = []
        for i in range(mac_no_total):
            try:
                mac_name = "%s%s" % (category_header[self.config],
                                     mac_type[self.mac_type] +
                                     str(i + 1).zfill(2) + "XX")

                osfr = osfrs[mac_name]
                osfr = str(np.round(osfr * 100, 2)) + " % "

                yield_val = yield_vals[mac_name]
                yield_val = str(np.round(yield_val * 100, 2)) + " % "

                act_val = act_vals[mac_name]
                act_val = str(np.round(act_val * 100, 2)) + " % "

                act_pic = act_pics[mac_name]
                act_pic = cv2.resize(act_pic, (400, 1))
                height, width, channel = act_pic.shape
                pile_width = channel * width
                act_pic = cv2.cvtColor(act_pic, cv2.COLOR_BGR2RGB)
                q_image = QImage(act_pic.data, width, height, pile_width,
                                 QImage.Format_RGB888)

                self.osfr_list[i].setText(osfr)
                self.yield_val_list[i].setText(yield_val)
                self.activation_val_list[i].setText(act_val)
                self.activation_status_list[i].setPixmap(
                    QPixmap.fromImage(q_image))

                self.active_labels.append(i)
            except:
                self.mac_name_list[i].setHidden(True)
                self.activation_status_list[i].setHidden(True)
                self.osfr_list[i].setHidden(True)
                self.yield_val_list[i].setHidden(True)
                self.activation_val_list[i].setHidden(True)
                continue

        # add tips
        self.label_osfr_val_example.setStatusTip("%.2f" % (global_osfr * 100) +
                                                 " %")
        self.label_yield_val_example.setStatusTip("%.2f" %
                                                  (global_yield * 100) + " %")
Exemplo n.º 50
0
 def set_image(self, value="1.png"):
     pixmap = QPixmap("res/tiles/" + value)
     pixmap = pixmap.scaled(self.card_size[0] + self.n,
                            self.card_size[1] + self.n)
     self.setStyleSheet("background-color: transparent;")
     self.setPixmap(pixmap)
Exemplo n.º 51
0
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        #uic.loadUi('project3.ui',self)
        self.scrollArea.setWidgetResizable(True)
        
        self.pushButton.setText('Ваша история - 1')
        self.pushButton_2.setText('Ваша история - 2')
        self.pushButton_12.setText('Ваша история - 3')
        self.pushButton_13.setText('Ваша история - 4')
        self.pushButton_14.setText('Ваша история - 5')
        self.pushButton_15.setText('Ваша история - 6')
        self.pushButton_16.setText('Ваша история - 7')
        self.pushButton_17.setText('Ваша история - 8')
        self.pushButton_18.setText('Ваша история - 9')
        self.pushButton_19.setText('Ваша история - 10')
        self.pushButton_20.setText('Ваша история - 11')
        self.pushButton_21.setText('Ваша история - 12')
        self.pushButton_22.setText('Ваша история - 13')
        self.pushButton_23.setText('Ваша история - 14')
        self.pushButton_24.setText('Ваша история - 15')
        self.pushButton_25.setText('Ваша история - 16')
        self.pushButton_26.setText('Ваша история - 17')
        self.pushButton_27.setText('Ваша история - 18')
        self.pushButton_28.setText('Ваша история - 19')
        self.pushButton_29.setText('Ваша история - 20')
        self.pushButton_30.setText('Ваша история - 21')         
        
        self.pushButton_6.clicked.connect(self.ch_story_less)
        self.pushButton_7.clicked.connect(self.ch_story_more)        
        
        self.pushButton_9.clicked.connect(self.change_more)
        self.pushButton_8.clicked.connect(self.change_less)
        
        self.pushButton_11.clicked.connect(self.ch_text_more)
        self.pushButton_10.clicked.connect(self.ch_text_less)        

        self.pushButton_30.clicked.connect(self.def30)
        self.pushButton_29.clicked.connect(self.def29)
        self.pushButton_28.clicked.connect(self.def28)
        self.pushButton_27.clicked.connect(self.def27)
        self.pushButton_26.clicked.connect(self.def26)
        self.pushButton_25.clicked.connect(self.def25)
        self.pushButton_24.clicked.connect(self.def24)
        self.pushButton_23.clicked.connect(self.def23)
        self.pushButton_22.clicked.connect(self.def22)
        self.pushButton_21.clicked.connect(self.def21)
        self.pushButton_20.clicked.connect(self.def20)
        self.pushButton_19.clicked.connect(self.def19)
        self.pushButton_18.clicked.connect(self.def18)
        self.pushButton_17.clicked.connect(self.def17)
        self.pushButton_16.clicked.connect(self.def16)
        self.pushButton_15.clicked.connect(self.def15)
        self.pushButton_14.clicked.connect(self.def14)
        self.pushButton_13.clicked.connect(self.def13)
        self.pushButton_12.clicked.connect(self.def12)
        self.pushButton_2.clicked.connect(self.def11)
        self.pushButton.clicked.connect(self.def10)
        
        self.pushButton_3.clicked.connect(self.ask)
        
        self.pushButton_5.clicked.connect(self.red)
        self.red = False
        self.d = False
        
        try:
            f = open('user.txt', 'r')
            line = f.read()
            f.close()
            self.pushButton_3.setText(line)
        except Exception:
            pass
        
        self.textBrowser.setText('ВЫБЕРИ СВОЮ ИСТОРИЮ')
        self.label_2.setPixmap(QPixmap('Заставка.jpg'))
        self.setNames()
        
        self.pushButton_4.clicked.connect(self.de)
        
        self.show_story()
Exemplo n.º 52
0
 def foto(self, t, l):
     img = t.text()
     pixmap = QPixmap(img)
     l.setPixmap(pixmap)
Exemplo n.º 53
0
 def showImage(self):
     jpg = QPixmap("media/smile")
     self.label.setPixmap(jpg)
Exemplo n.º 54
0
 def update_second_photo(self, filename):
     pixmap = QPixmap(filename)
     self.photo_label2.setPixmap(pixmap.scaled(240,140))
Exemplo n.º 55
0
    def __init__(self, gui, gateway):  # pylint: disable=too-many-statements
        super(View, self).__init__()
        self.gui = gui
        self.gateway = gateway
        self.share_widgets = []
        self.setModel(Model(self))
        self.setItemDelegate(Delegate(self))

        self.setAcceptDrops(True)
        #self.setColumnWidth(0, 150)
        #self.setColumnWidth(1, 100)
        self.setColumnWidth(2, 115)
        self.setColumnWidth(3, 70)
        self.setColumnWidth(4, 10)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.setHeaderHidden(True)
        #self.setRootIsDecorated(False)
        self.setSortingEnabled(True)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.setFocusPolicy(Qt.NoFocus)
        #font = QFont()
        #font.setPointSize(12)
        #self.header().setFont(font)
        #self.header().setDefaultAlignment(Qt.AlignCenter)
        self.header().setStretchLastSection(False)
        self.header().setSectionResizeMode(0, QHeaderView.Stretch)
        self.header().setSectionResizeMode(1, QHeaderView.Stretch)
        #self.header().setSectionResizeMode(2, QHeaderView.Stretch)
        #self.header().setSectionResizeMode(3, QHeaderView.Stretch)
        self.setIconSize(QSize(24, 24))

        self.drop_outline = QLabel(self)
        self.drop_outline.setPixmap(QPixmap(resource('drop_zone_outline.png')))
        self.drop_outline.setScaledContents(True)
        self.drop_outline.setAcceptDrops(True)
        self.drop_outline.installEventFilter(self)

        self.drop_icon = QLabel(self)
        self.drop_icon.setPixmap(QPixmap(resource('upload.png')))
        self.drop_icon.setAlignment(Qt.AlignCenter)
        self.drop_icon.setAcceptDrops(True)
        self.drop_icon.installEventFilter(self)

        self.drop_text = QLabel(self)
        self.drop_text.setText("Drag and drop folders here")
        font = QFont()
        if sys.platform == 'darwin':
            font.setPointSize(18)
        else:
            font.setPointSize(14)
        self.drop_text.setFont(font)
        self.drop_text.setStyleSheet('color: grey')
        self.drop_text.setAlignment(Qt.AlignCenter)
        self.drop_text.setAcceptDrops(True)
        self.drop_text.installEventFilter(self)
        self.drop_text.setSizePolicy(QSizePolicy.Expanding, 0)

        self.drop_subtext = QLabel(self)
        self.drop_subtext.setText(
            "Added folders will sync with {}".format(self.gateway.name))
        self.drop_subtext.setStyleSheet('color: grey')
        self.drop_subtext.setAlignment(Qt.AlignCenter)
        self.drop_subtext.setAcceptDrops(True)
        self.drop_subtext.installEventFilter(self)
        self.drop_subtext.setSizePolicy(QSizePolicy.Expanding, 0)

        self.select_folder_button = QPushButton("Select...", self)
        self.select_folder_button.setAcceptDrops(True)
        self.select_folder_button.installEventFilter(self)
        self.select_folder_button.clicked.connect(self.select_folder)

        layout = QGridLayout(self)
        layout.addWidget(self.drop_outline, 1, 1, 9, 3)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 1, 1)
        layout.addWidget(self.drop_icon, 2, 2, 3, 1)
        layout.addWidget(self.drop_text, 6, 1, 1, 3)
        layout.addWidget(self.drop_subtext, 7, 1, 1, 3)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, 0), 8, 1)
        layout.addWidget(self.select_folder_button, 8, 2)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, 0), 8, 3)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 9, 1)

        self.doubleClicked.connect(self.on_double_click)
        self.customContextMenuRequested.connect(self.on_right_click)

        self.model().populate()
Exemplo n.º 56
0
    def click1(self):

        self.pushButton_6.setEnabled(True)
        self.pushButton_7.setEnabled(True)

        self.refresh = True

        # If there is a cropped file, then we view cropped images which has both original and cropped images
        if os.path.isfile('Img_files_cropped.txt'):
            pass
        elif os.path.isfile('Img_files.txt'):
            copyfile("Img_files.txt", "Img_files_cropped.txt")

        with open("Img_files_cropped.txt") as file:
            self.img_files = file.read().splitlines()
        self.length = len(self.img_files)
        file.close()

        # img_files_border has "True" values for cropped images and False for original images
        self.img_files_border[:self.length] = [False] * self.length
        for i in range(self.length):
            if os.path.basename(os.path.dirname(
                    self.img_files[i])) == "Cropped":
                self.img_files_border[i] = True

        if self.formCall:
            n = 6 if (self.length - self.set * 6) > 6 else (self.length -
                                                            (self.set - 1) * 6)
            for i, label in zip(range(n), self.labels):
                k = (self.set - 1) * 6 + i
                image = QImage(self.img_files[k])
                image = image.convertToFormat(
                    QImage.Format_ARGB8565_Premultiplied)

                p = QPainter(image)
                p.setCompositionMode(QPainter.CompositionMode_DestinationIn)
                p.fillRect(image.rect(), QColor(0, 0, 0, self.transparency))
                p.end()

                pixmap = QPixmap(image)
                w = int(label.width() - 4.0)
                h = int(label.height() - 4.0)

                if self.img_files_border[k]:
                    smaller_pixmap = pixmap.scaledToWidth(
                        w, Qt.FastTransformation)
                    label.setScaledContents(False)
                    label.setFrameShadow(QFrame.Sunken)
                else:
                    smaller_pixmap = pixmap.scaled(w, h, Qt.KeepAspectRatio,
                                                   Qt.FastTransformation)
                    label.setScaledContents(True)
                    label.setFrameShadow(QFrame.Plain)

                label.setPixmap(smaller_pixmap)
                self.btn_img[i] = self.img_files[k]

            if n < 6:
                self.pushButton_3.setEnabled(False)
                displays = [False, False, False, False, False, False]
                displays[:n] = [True] * n

                for i, label, display in zip(range(6), self.labels, displays):
                    if not display:
                        label.clear()
                        label.setFrameShadow(QFrame.Plain)
                        self.btn_img[i] = None

        else:
            self.set = 1  # first set of image displayed with each click 1
            self.pushButton_2.setEnabled(False)  # previous set button is False
            self.pushButton_3.setEnabled(
                True) if self.length > 6 else self.pushButton_3.setEnabled(
                    False)  # next set

            self.btn_img = [None, None, None, None, None, None]
            n = 6 if self.length > 6 else self.length  # first six images are displayed

            self.formCall = False

            for i, label, filename, border, in zip(range(n), self.labels,
                                                   self.img_files,
                                                   self.img_files_border):
                image = QImage(filename)
                image = image.convertToFormat(
                    QImage.Format_ARGB8565_Premultiplied)

                p = QPainter(image)
                p.setCompositionMode(QPainter.CompositionMode_DestinationIn)
                p.fillRect(image.rect(), QColor(0, 0, 0, self.transparency))
                p.end()

                pixmap = QPixmap(image)
                w = int(label.width() - 4.0)
                h = int(label.height() - 4.0)

                if border:
                    smaller_pixmap = pixmap.scaledToWidth(
                        w, Qt.FastTransformation)
                    label.setScaledContents(False)
                    label.setFrameShadow(QFrame.Sunken)
                else:
                    smaller_pixmap = pixmap.scaled(w, h, Qt.KeepAspectRatio,
                                                   Qt.FastTransformation)
                    label.setScaledContents(True)
                    label.setFrameShadow(QFrame.Plain)

                label.setPixmap(smaller_pixmap)
                self.btn_img[i] = filename
Exemplo n.º 57
0
 def __init__(self, parent, model, pixel_size, vnc=None):
     super().__init__(parent)
     self.fb = FrameBuffer(model)
     self.pixel_size = pixel_size
     self.mPixmap = QPixmap()
     self.vnc = vnc
Exemplo n.º 58
0
 def update_first_photo(self, filename):
     pixmap = QPixmap(filename)
     self.photo_label.setPixmap(pixmap.scaled(240,140))
     self.video_preview.setPixmap(pixmap.scaled(480,270))
Exemplo n.º 59
0
 def __init__(self):
     super().__init__()
     self.setObjectName('app')
     QApplication.setWindowIcon(QIcon(QPixmap(APP_ICON)))
Exemplo n.º 60
-1
def png(nom):
    """Charge l'image <nom>.png depuis le repertoire 'images/'.

    L'image doit être au format png, et son nom doit indiqué sans l'extension '.png'."""
    pixmap = QPixmap()
    pixmap.load(png_pth(nom), 'PNG')
    return pixmap