def initAllInformations(self, nameModule, typeModule, nodesSelected): self.__nodesSelected = nodesSelected self.nameModule = nameModule try: self.module = self.loader.modules[str(nameModule)] except KeyError: self.module = None if self.module and self.module.icon: p = QPixmap(self.module.icon) p.scaled(64, 64, Qt.KeepAspectRatio) self.modulepix.setPixmap(p) else: p = self.modulepix.pixmap().scaled(64,64, Qt.KeepAspectRatio) self.modulepix.setPixmap(p) title = self.windowTitle() + ' ' + str(nameModule) self.setWindowTitle(title) self.nameModuleField.setText(nameModule) self.typeModuleField.setText(typeModule) if not nodesSelected: self.__nodesSelected = [] self.conf = self.loader.get_conf(str(nameModule)) try: self.textEdit.setText(self.conf.description) except TypeError: self.textEdit.setText(self.conf.description()) args = self.conf.arguments() self.createArgShape(args)
class DpadView(QGraphicsView): def __init__(self, *args): QGraphicsView.__init__(self, *args) self.move(2, 90) self.btnSize = 75 self.padding = -35 self.setMaximumHeight(self.btnSize * 2 + 20) self.setMaximumWidth(self.btnSize * 2 + 20) self.setMinimumHeight(self.btnSize * 2 + 20) self.setMinimumWidth(self.btnSize * 2 + 20) self.adjustSize() self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;') self.scene = QGraphicsScene(self) self.left = QPixmap(os.getcwd() + '/../icons/left.png') self.left = self.left.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio) self.right = QPixmap(os.getcwd() + '/../icons/right.png') self.right = self.right.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio) self.up = QPixmap(os.getcwd() + '/../icons/up.png') self.up = self.up.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio) self.down = QPixmap(os.getcwd() + '/../icons/down.png') self.down = self.down.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio) self.leftItem = QGraphicsPixmapItem(self.left) self.leftItem.setOffset(QPointF(0, self.btnSize + self.padding)) self.scene.addItem(self.leftItem) self.rightItem = QGraphicsPixmapItem(self.right) self.rightItem.setOffset(QPointF(self.btnSize * 2 + self.padding * 2, self.btnSize + self.padding)) self.scene.addItem(self.rightItem) self.upItem = QGraphicsPixmapItem(self.up) self.upItem.setOffset(QPointF(self.btnSize + self.padding, 0)) self.scene.addItem(self.upItem) self.downItem = QGraphicsPixmapItem(self.down) self.downItem.setOffset(QPointF(self.btnSize + self.padding, self.btnSize * 2 + self.padding * 2)) self.scene.addItem(self.downItem) self.effect = QGraphicsDropShadowEffect() self.effect.setOffset(0, 0) self.effect.setBlurRadius(20) self.effect.setColor(Qt.green) self.downItem.setGraphicsEffect(self.effect) self.setScene(self.scene) self.tl2 = QTimeLine(10000) self.tl2.setFrameRange(0, 10000) self.t = QGraphicsItemAnimation() self.t.setItem(self.downItem) self.t.setTimeLine(self.tl2) self.tl2.connect(self.tl2, SIGNAL('frameChanged(int)'), self.updateEffect) self.effectd = 3 self.tl2.start() def updateEffect(self): if self.effect.blurRadius() > 50: self.effectd = -3 elif self.effect.blurRadius() < 5: self.effectd = 3 self.effect.setBlurRadius(self.effect.blurRadius() + self.effectd)
def parse_account_info(self, resp): if resp.status == 200: account_data = resp.data self.uid = str(account_data["uid"]) name = account_data["display_name"] self.ui_handler.manager_ui.label_username.setText(name) user_icon = QPixmap(self.controller.datahandler.datapath("ui/icons/user.png")) self.ui_handler.manager_ui.label_username_icon.setPixmap(user_icon.scaled(24,24)) self.logger.auth("Account data received for " + name) else: self.ui_handler.manager_ui.label_username.setText("unknown user") user_icon = QPixmap(self.controller.datahandler.datapath("ui/icons/user_white.png")) self.ui_handler.manager_ui.label_username_icon.setPixmap(user_icon.scaled(24,24)) self.logger.auth("Failed to fetch account data, treating as unknown user")
def drawStationName(self): """Draw station name snippet to station_name_img""" res = self.current_result name = res.station.name #self.station_name.setText('') #self.station_name.clear() #self.station_name.addItems(name.optional_values) if not self.file_list.currentItem().station is None: self.station_name.setText(self.file_list.currentItem().station) else: self.station_name.setText(name.value) #font = QFont("Consolas", 11) #self.station_name.lineEdit().setFont(font) #self.setConfidenceColor(self.station_name, name) img = self.cutImage(res.contrast_station_img, name) if self.dark_theme: img = 255 - img processedimage = array2qimage(img) pix = QPixmap() pix.convertFromImage(processedimage) if self.station_name_img.height() < pix.height(): pix = pix.scaled(self.station_name_img.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) scene = QGraphicsScene() scene.addPixmap(pix) self.station_name_img.setScene(scene) self.station_name_img.show()
class Human(Entity): BRAVE = "brave" COWARD = "coward" CARELESS = "careless" CAUTIOUS = "cautious" RATIONAL = "rational" STUPID = "stupid" WEAPON_LONG = "long" WEAPON_SHORT = "short" NO_WEAPON = "noweapon" def __init__(self, personality, weapon, cord_x=0, cord_y=0, parent=None): super().__init__("human_{}_{}.png".format(personality, weapon), parent=parent) self.personality = personality self.weapon = weapon self.cord_x = cord_x self.cord_y = cord_y self.setFixedSize(73 * _SCALE, 73 * _SCALE) def change_weapon(self, weapon): self.weapon = weapon self._base_image = "human_{}_{}.png".format(self.personality, self.weapon) self.updatePixmap() def updatePixmap(self): path = _PATH + os.sep + "assets" + os.sep + self._base_image self.__pixmap = QPixmap(path) self.__pixmap = self.__pixmap.scaled(self.__pixmap.width() * _SCALE, self.__pixmap.height() * _SCALE) self.__pixmap = self.__pixmap.transformed(QTransform().rotate(self.angle)) self._base_label.setPixmap(self.__pixmap)
def getProjectsBanner(self): projectName = str(self.ui.ProjectsEDIT.text()) # Don't requery for the project banner if its there if self.currentProjectName == projectName: return self.currentProjectName = projectName self.ui.ProjectsEDIT.currentProject = Project.recordByName(projectName) sgProj = sg.find_one( "Project", [["name", "is", projectName]], ["billboard"] ) if sgProj: if sgProj["billboard"]: billboardPath = sgProj["billboard"]["url"] if billboardPath: urllib.urlretrieve(billboardPath, self.BANNERPATH) if os.path.exists(self.BANNERPATH): bannerPixmap = QPixmap( self.ui.ProjectBannerView.maximumWidth(), self.ui.ProjectBannerView.maximumHeight() ) didLoad = bannerPixmap.load(self.BANNERPATH) # We actually don't care about the height # since this will be clamped from the width self.ui.ProjectBannerView.setPixmap( bannerPixmap.scaled(244, 200, Qt.KeepAspectRatio) ) self.ui.ProjectBannerView.setAlignment(Qt.AlignCenter) self.ui.ProjectBannerView.setScaledContents(True) # For some reason, calling the window repaint # fixes the issue with the flickering self.ui.header.show() self.repaint() self.parent.repaint()
def __set_cover(self): pixmap = QPixmap(self._local_cover_path) pixmap = pixmap.scaled(self.ui.pushButtonCover.iconSize(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.SmoothTransformation) pixmap_size = self.ui.pushButtonCover.iconSize() pixmap = pixmap.copy(0,0,pixmap_size.width(), pixmap_size.height()) cover = QIcon(pixmap) self.ui.pushButtonCover.setIcon(cover)
def _showCurrentPicture(self, selRow): '''Show current selected item's picture''' selRow = selRow() model = self.ui.listData.model() picPath = model.data(model.createIndex(selRow, model.getPicRowIndex())).toString() #self.ui.pictureShow.setText(u'选择了第%d列, 地址为:%s'%(selRow, picData)) #TODO: using QPixelMap to load and show the image for correct scale picShow = self.ui.pictureShow pixmap = QPixmap(picPath) if pixmap.isNull(): picShow.setText(u'第%d行数据对应的图片\n[%s]\n\n无法加载显示!'%(selRow, picPath)) else: rect = picShow.frameRect() pixmap.scaled(rect.width(), rect.height(), Qt.KeepAspectRatioByExpanding) self.ui.pictureShow.setPixmap(pixmap)
def store_image(self, data): if data is None: return None data_hash = sha512(data).hexdigest() try: return self.filemap[data_hash].destination except KeyError: pass try: destination_name = os.path.join('images', self.available_names.popleft()) except IndexError: # No more available file names. return None pixmap = QPixmap() if pixmap.loadFromData(data): pixmap = pixmap.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation) makedirs(ApplicationData.get('images')) if pixmap.save(ApplicationData.get(destination_name)): file_mapping = FileMapping(data_hash, destination_name) self.filemap[data_hash] = file_mapping map_filename = ApplicationData.get(os.path.join('images', '.cached_icons.map')) map_tempname = map_filename + '.tmp' try: file = open(map_tempname, 'wb') pickle.dump(self.filemap, file) file.close() if sys.platform == 'win32': unlink(map_filename) os.rename(map_tempname, map_filename) except Exception, e: log.error("could not save icon cache file mappings: %s" % e) return destination_name
def _set_filename(self, filename): self.__dict__['filename'] = filename filename = ApplicationData.get(filename) if filename else Resources.get(self.default_icon) pixmap = QPixmap() if pixmap.load(filename): self.setPixmap(pixmap.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation)) else: self.setPixmap(pixmap)
def setsplash(self, splash): """ Set the project image to the given image. :param splash: The path to the image to use as a the splash screen. """ pixmap = QPixmap(splash) w = self.splashlabel.width() h = self.splashlabel.height() self.splashlabel.setPixmap(pixmap.scaled(w, h, Qt.KeepAspectRatio))
def set_icon(self, path): """ Set the forms icon preview :param path: The path to icon. """ pixmap = QPixmap(path) w = self.iconlabel.width() h = self.iconlabel.height() self.iconlabel.setPixmap(pixmap.scaled(w, h, Qt.KeepAspectRatio))
def __init__(self, qpart): QWidget.__init__(self, qpart) self._qpart = qpart qpart.blockCountChanged.connect(self.update) defaultSizePixmap = QPixmap(qutepart.getIconPath('bookmark.png')) iconSize = self._qpart.cursorRect().height() self._bookmarkPixmap = defaultSizePixmap.scaled(iconSize, iconSize)
def render(self, painter): pixmap = QPixmap(self.view.size()) pixPainter = QPainter() pixPainter.begin(pixmap) self.view.render(pixPainter) pixPainter.end() scaledPixmap = pixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) drawRect = QRect(self.rect.topLeft(), scaledPixmap.size()) painter.drawPixmap(drawRect, scaledPixmap)
def ShowImageSegNMask(): global image_file image_file = str(seg_param.comboBox.currentText()) label2 = seg_param.label_2 pixmap = QPixmap(image_file); pixmap1 = pixmap.scaled(label2.size(),QtCore.Qt.KeepAspectRatio); label2.setPixmap(pixmap1) seg_param.pushButton_4.setEnabled(True) return True
def __init__(self, parent=None, size=16): QWidget.__init__(self, parent) self.setFocusPolicy(Qt.NoFocus) self.setVisible(True) self.setMinimumSize(size+2, size+2) pixmap = QPixmap() if pixmap.load(Resources.get("icons/search.svg")): self.icon = pixmap.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation) else: self.icon = None
def drawSnippet(self, graphicsview, snippet): """Draw single result item to graphicsview""" processedimage = array2qimage(snippet) pix = QPixmap() pix.convertFromImage(processedimage) pix = pix.scaled(graphicsview.width(), graphicsview.height()-1, Qt.KeepAspectRatio, Qt.SmoothTransformation) scene = QGraphicsScene() scene.addPixmap(pix) graphicsview.setScene(scene) graphicsview.show()
def setPhotoDisplay(self): """ If there's a currently set imageDirectoryObj, set the current image file (self.imf) to match the currentPhotoIndex, size it properly and set it to display. """ if self.imageDirectoryObj: self.imf = self.imageDirectoryObj.images[ self.currentPhotoIndex ] photo_pixmap = QPixmap( self.imf.file_path ) self.scaled_photo = photo_pixmap.scaled(self.photoDisplay.size(), QtCore.Qt.KeepAspectRatio) self.photoDisplay.setPixmap( self.scaled_photo )
def _NH_SIPAccountManagerDidAddAccount(self, notification): account = notification.data.account icon = None if account is BonjourAccount(): pixmap = QPixmap() if pixmap.load(Resources.get("icons/bonjour.png")): pixmap = pixmap.scaled(16, 16, Qt.KeepAspectRatio, Qt.SmoothTransformation) icon = QIcon(pixmap) self.beginInsertRows(QModelIndex(), len(self.accounts), len(self.accounts)) self.accounts.append(AccountInfo(account, icon)) self.endInsertRows()
def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize): p = QPixmap() p.loadFromData(data, encoding, Qt.AutoColor) w, h = p.width(), p.height() p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0)) if p.width() != xsize or p.height() != ysize: p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) QGraphicsPixmapItem.__init__(self, p) self.height, self.width = ysize, xsize self.setTransformationMode(Qt.SmoothTransformation) self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
def updateFormFromSelectedUser(self): self.levelDifficultyLabel.setText( Common.Level.LevelDifficultyToString( self.levelOptions.enemiesDifficulty ) ) self.numberOfEnemiesLabel.setText( str( self.levelOptions.enemiesCount ) ) self.enemySpeedLabel.setText( str(self.levelOptions.enemySpeed)) self.playerSpeedLabel.setText( str(self.levelOptions.playerSpeed)) self.playerDamage.setText( str(self.levelOptions.damage)) pix = QPixmap( self.levelOptions.enumTexture.value ) self.backgroundTexture.setStyleSheet("border-image:url(:/2.png);") self.backgroundTexture.setPixmap( pix.scaled( 150, 150 ) )
def _load_icon(filename, backgroundColor, width, height): foreground = QPixmap() foreground.load(filename) pixmap = QPixmap(foreground.size()) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) painter.drawPixmap(QPointF(0, 0), foreground) painter.end() pixmap = pixmap.scaled(QSize(width, height), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def setWidget(self): try: self.module = self.loader.modules[str(self.modulename)] except KeyError: self.module = None if self.module and self.module.icon: p = QPixmap(self.module.icon) p.scaled(64, 64, Qt.KeepAspectRatio) self.modulepix.setPixmap(p) else: p = self.modulepix.pixmap().scaled(64,64, Qt.KeepAspectRatio) self.modulepix.setPixmap(p) if not self.nodeSelected: self.nodeSelected = [] self.conf = self.loader.get_conf(str(self.modulename)) try: self.textEdit.setText(self.conf.description) except TypeError: self.textEdit.setText(self.conf.description()) args = self.conf.arguments() self.createArgShape(args)
def data(self, index, role): if not index.isValid(): return QVariant() #XXX partition / folder if role == Qt.DecorationRole : if self.getItem(index).node.is_file : #icon = QPixmap(":dff_partition.png") ic = QPixmap(":folder.png") icon = ic.scaled(QSize(24, 24)) else: ic = QPixmap(":folder.png") icon = ic.scaled(QSize(24, 24)) return QVariant(icon) if role != Qt.DisplayRole and role != Qt.EditRole : return QVariant() item = self.getItem(index) if item: return QVariant(item.data(index.column())) else : return QVariant()
class BumpersView(QGraphicsView): def __init__(self, *args): QGraphicsView.__init__(self, *args) self.move(2, 22) self.btnSize = 60 self.setMaximumHeight(60) self.setMaximumWidth(332) self.setMinimumHeight(60) self.setMinimumWidth(332) self.adjustSize() self.scene = QGraphicsScene(self) self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;') self.l1 = QPixmap(os.getcwd() + '/../icons/l1.png') self.l1 = self.l1.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio) self.l1Item = QGraphicsPixmapItem(self.l1) self.l1Item.setOffset(QPointF(30, 0)) self.scene.addItem(self.l1Item) self.r1 = QPixmap(os.getcwd() + '/../icons/r1.png') self.r1 = self.l1.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio) self.r1Item = QGraphicsPixmapItem(self.r1) self.r1Item.setOffset(QPointF(200, 0)) self.scene.addItem(self.r1Item) self.setScene(self.scene)
def drawSnippet(self, graphicsview, item): """Draw single result item to graphicsview""" res = self.current_result snippet = self.cutImage(res.contrast_commodities_img, item) #cv2.imwrite('snippets/'+str(self.currentsnippet)+'.png',snippet) #self.currentsnippet += 1 processedimage = array2qimage(snippet) pix = QPixmap() pix.convertFromImage(processedimage) if graphicsview.height() < pix.height(): pix = pix.scaled(graphicsview.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) scene = QGraphicsScene() scene.addPixmap(pix) graphicsview.setScene(scene) graphicsview.show()
def set_user_icon(self, image_file_name): pixmap = QPixmap(32, 32) pixmap.fill(QColor(Qt.transparent)) painter = QPainter(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) painter.setBrush(QBrush(Qt.white)) painter.setPen(QPen(painter.brush(), 0, Qt.NoPen)) #painter.drawRoundedRect(0, 0, 32, 32, 6, 6) painter.drawRoundedRect(0, 0, 32, 32, 0, 0) icon = QPixmap() if icon.load(image_file_name): icon = icon.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.drawPixmap(0, 0, icon) painter.end() self.image.setPixmap(pixmap)
def setMaximizeIcon(self, opacity=0.6): self.buttonStyle = "max" self.setToolTip("Maximize") pixmap = QPixmap(250, 250) pixmap.fill(self.backgroundColor) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) painter.setOpacity(opacity) pen = QPen(self.foregroundColor) pen.setWidth(30) painter.setPen(pen) painter.drawRect(50.0, 50.0, 150.0, 150.0) painter.end() pixmap = pixmap.scaled(QSize(self.pixmapWidth, self.pixmapHeight),Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(pixmap)
def createAxisLabelPixmap(self): pixmap = QPixmap(250, 250) pixmap.fill(self.backgroundColor) painter = QPainter() painter.begin(pixmap) font = QFont() font.setBold(True) font.setPixelSize(250 - 30) path = QPainterPath() path.addText(QPointF(50, 250 - 50), font, self.axis) brush = QBrush(self.foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(self.labelsWidth, self.labelsheight), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def drawStationName(self): """Draw station name snippet to station_name_img""" res = self.current_result name = res.station.name self.station_name.setEditText(name.value) img = self.cutImage(res.contrast_station_img, name) processedimage = array2qimage(img) pix = QPixmap() pix.convertFromImage(processedimage) if self.station_name_img.height() < pix.height(): pix = pix.scaled(self.station_name_img.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) scene = QGraphicsScene() scene.addPixmap(pix) self.station_name_img.setScene(scene) self.station_name_img.show()
def data(self, index, role): attributes = self.availableAttributes() if not index.isValid(): return QVariant() if index.row() > len(self.__list) or index.row() < 0: return QVariant() try: node = self.__rows[index.row()] except: return QVariant() if role == Qt.DisplayRole: attrpath = str(unicode(attributes[index.column()]).encode('utf-8')) if attrpath == "name": return QVariant(QString.fromUtf8(node.name())) elif attrpath == "size": return QVariant(node.size()) elif attrpath == "extension": return QVariant(QString.fromUtf8(node.extension())) elif attrpath == "path": if isinstance(node, VLink): return QVariant(QString.fromUtf8(node.linkPath())) else: return QVariant(QString.fromUtf8(node.path())) elif attrpath == "absolute": if isinstance(node, VLink): return QVariant(QString.fromUtf8(node.linkAbsolute())) else: return QVariant(QString.fromUtf8(node.absolute())) elif attrpath == "module": if node.fsobj(): return QVariant(QString.fromUtf8(node.fsobj().name)) return QVariant() elif attrpath == "has children": if isinstance(node, VLink): return QVariant(node.linkHasChildren()) else: return QVariant(node.hasChildren()) elif attrpath == "child count": if isinstance(node, VLink): return QVariant(node.linkChildCount()) else: return QVariant(node.childCount()) elif attrpath == "is deleted": return QVariant(node.isDeleted()) else: try: val = node.attributesByName(attrpath, ABSOLUTE_ATTR_NAME) except Exception as e: print "NodeListModel data can't get attribute " + attrpath + " by name " + str( e) return QVariant() if len(val) == 1: if val[0].type() == typeId.VTime: vtime = val[0].value() if vtime: return QVariant(str(vtime.get_time())) elif val[0].type() == typeId.String: return QVariant(QString.fromUtf8(val[0].value())) else: return QVariant(val[0].value()) if role == Qt.ToolTipRole: return QVariant(QString.fromUtf8(node.name())) # Display icons if (role == Qt.DecorationRole) and (attributes[index.column()] == "name"): pixmap = None if self.__thumb: if self.thumbnailer.isThumbnailable(node): pixmap = self.thumbnailer.generate(node) if not pixmap: pixmap = QPixmap(":file_temporary.png") if not pixmap: pixmap = self.getIconPixmap(node) if not pixmap: pixmap = QPixmap(node.icon()) if isinstance(node, VLink): pixmap = pixmap.scaled(QSize(128, 128), Qt.KeepAspectRatio) painter = QPainter(pixmap) linkPixmap = QPixmap(":vlink") painter.drawPixmap(0, 0, linkPixmap) painter.end() elif node.hasChildren(): try: pfsobj = node.children()[0].fsobj().this except AttributeError: pfsobj = None try: nfsobj = node.fsobj().this except AttributeError: nfsobj = None if pfsobj != nfsobj: pixmap = pixmap.scaled(QSize(128, 128), Qt.KeepAspectRatio) painter = QPainter(pixmap) rootPixmap = QPixmap(":root") painter.drawPixmap(0, 0, rootPixmap) painter.end() return QVariant(QIcon(pixmap)) if role == Qt.BackgroundRole: if index.row() == self.activeSelection(): palette = QPalette().color(QPalette.Highlight) return QVariant(QColor(palette)) if role == Qt.ForegroundRole: if index.row() == self.activeSelection(): palette = QPalette().color(QPalette.HighlightedText) return QVariant(QColor(palette)) if node.isDeleted(): return QVariant(QColor(Qt.red)) if (role == Qt.CheckStateRole) and (attributes[index.column()] == "name"): if long(node.this) in self.selection.get(): return Qt.Checked else: return Qt.Unchecked return QVariant()
def fill_gallery(self, visit_id, event_id): self.img_path_list = [] self.img_path_list1D = [] # Get all pictures for event_id | visit_id sql = ("SELECT value FROM " + self.schema_name + ".om_visit_event_photo" " WHERE event_id = '" + str(event_id) + "' AND visit_id = '" + str(visit_id) + "'") rows = self.controller.get_rows(sql) num = len(rows) # Get doc_absolute_path from config_param_system sql = ("SELECT value FROM " + self.schema_name + ".config_param_system" " WHERE parameter = 'doc_absolute_path'") row = self.controller.get_row(sql) if row[0] != None: # If absolute_path exist in config_param_system for n in range(0, num): path = str(row[0]) + str(rows[n][0]) self.img_path_list1D.append(path) else: for m in range(0, num): self.img_path_list1D.append(rows[m][0]) # Add picture to gallery # Fill one-dimensional array till the end with "0" self.num_events = len(self.img_path_list1D) # Fill the rest of the fields in gallery with 0 limit = self.num_events % 9 limit = 9 - limit for k in range(0, limit): # @UnusedVariable self.img_path_list1D.append(0) # Inicialization of two-dimensional array rows = (self.num_events / 9) + 1 columns = 9 self.img_path_list = [[0 for x in range(columns)] for x in range(rows)] # @UnusedVariable # Convert one-dimensional array to two-dimensional array # Fill self.img_path_list with values from self.img_path_list1D idx = 0 if rows == 1: for br in range(0, len(self.img_path_list1D)): self.img_path_list[0][br] = self.img_path_list1D[br] else: for h in range(0, rows): for r in range(0, columns): self.img_path_list[h][r] = self.img_path_list1D[idx] idx = idx + 1 # List of pointers(in memory) of clicableLabels self.list_widget = [] self.list_labels = [] # Fill first slide of gallery for i in range(0, 9): widget_name = "img_" + str(i) widget = self.dlg_gallery.findChild(QLabel, widget_name) if widget: # Set image to QLabel # Parse a URL into components url = urlparse.urlsplit(str(self.img_path_list[0][i])) # Check if path is URL if url.scheme == "http" or url.scheme == "https": url = str(self.img_path_list[0][i]) data = urllib2.urlopen(url).read() pixmap = QPixmap() pixmap.loadFromData(data) else: pixmap = QPixmap(str(self.img_path_list[0][i])) pixmap = pixmap.scaled(171, 151, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) widget_extended = ExtendedQLabel.ExtendedQLabel(widget) widget_extended.setPixmap(pixmap) widget_extended.clicked.connect( partial(self.zoom_img, i, visit_id, event_id)) self.list_widget.append(widget_extended) self.list_labels.append(widget) txt_visit_id = self.dlg_gallery.findChild(QLineEdit, 'visit_id') txt_visit_id.setText(str(visit_id)) txt_event_id = self.dlg_gallery.findChild(QLineEdit, 'event_id') txt_event_id.setText(str(event_id)) self.start_indx = 0 self.btn_next = self.dlg_gallery.findChild(QPushButton, "btn_next") self.btn_next.clicked.connect(self.next_gallery) self.btn_previous = self.dlg_gallery.findChild(QPushButton, "btn_previous") self.btn_previous.clicked.connect(self.previous_gallery) self.set_icon(self.btn_previous, "109") self.set_icon(self.btn_next, "108") self.btn_close = self.dlg_gallery.findChild(QPushButton, "btn_close") self.btn_close.clicked.connect( partial(self.close_dialog, self.dlg_gallery)) # If all images set in one page, disable button next if num <= 9: self.btn_next.setDisabled(True) # Open dialog self.open_dialog(self.dlg_gallery, maximize_button=False)
def _loadIcon(self, fileName): defaultSizePixmap = QPixmap(qutepart.getIconPath(fileName)) iconSize = self._qpart.cursorRect().height() return defaultSizePixmap.scaled(iconSize, iconSize, transformMode=Qt.SmoothTransformation)
def data(self, index, role): """ \reimp Nodes' pointers are encapsulated in QStandardItem (role : Qt.UserRole + 1). Most of the data can only be retrieved only if the node is retrieved: * The node name * The node icon * ... To do so, the TreeModel.data() method calls the QStandardItemModel.data() method by passing the `index` parameter and `Qt.UserRole + 1` or `Qt.UserRole + 2` to it. In the second case, it retrieves a boolean used to know if the node is already expended and returns directly. \param index the index of the data we want to get \param role the role of the data we want to retrieve \return a QVariant containing the data, or an invalid QVariant if the data could not be retrieved. """ if not index.isValid(): return QVariant() # Qt.UserRole + 2 contain a boolean indicating if the node has already been expanded # in the tree. if role == Qt.UserRole + 3: return QStandardItemModel.data(self, index, role) if role == Qt.UserRole + 2: return QStandardItemModel.data(self, index, role) # call QStandardItemModel.data method with a Qt.UserRole + 1 to get the pointer on the node # (returns a invalid QVariant if the node or the data is None) data = QStandardItemModel.data(self, index, Qt.UserRole + 1) if not data.isValid(): return data # getting the node or returning an invalid QVariant() if the node is not valid uid, valid = data.toULongLong() if not valid: return QVariant() node = self.VFS.getNodeById(uid) if node is None: return QVariant() # if role == UserRole + 1, it means that the node itself must be returned (the pointer # on the node, encapsulated in a QVariant() if role == (Qt.UserRole + 1): return data # in other cases, returns the requires data : icon, color, etc. or an invalid QVariant() # if the role does not correpond to anything. if role == Qt.DisplayRole: display = QString.fromUtf8(node.name()) if self.displayCount: display += QString(" (" + str(node.totalChildrenCount()) + ")") return QVariant(display) if role == Qt.DecorationRole: pixmap = QPixmap(node.icon()) if node.hasChildren(): try: pfsobj = node.children()[0].fsobj( ).this #XXX fsobj have uid now except AttributeError: pfsobj = None try: nfsobj = node.fsobj().this except AttributeError: nfsobj = None if pfsobj != nfsobj: pixmap = pixmap.scaled(QSize(128, 128), Qt.KeepAspectRatio) painter = QPainter(pixmap) rootPixmap = QPixmap(":root") painter.drawPixmap(0, 0, rootPixmap) painter.end() return QVariant(QIcon(pixmap)) if role == Qt.BackgroundRole: if index == self.currentIndex: palette = QPalette().color(QPalette.Highlight) return QVariant(QColor(palette)) if role == Qt.ForegroundRole: if (index == self.currentIndex) and not node.isDeleted(): palette = QPalette().color(QPalette.HighlightedText) return QVariant(QColor(palette)) if node.isDeleted(): return QVariant(QColor(Qt.red)) if self.ch == True: if role == Qt.CheckStateRole: if index.column() == 0: if node.uid() in self.selection.get(): return Qt.Checked else: return Qt.Unchecked return QVariant()
def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(834, 785) self.CenterMass = QtGui.QLineEdit(Form) self.CenterMass.setGeometry(QtCore.QRect(150, 390, 51, 24)) self.CenterMass.setObjectName(_fromUtf8("CenterMass")) self.Eccentricity = QtGui.QLineEdit(Form) self.Eccentricity.setGeometry(QtCore.QRect(150, 450, 113, 24)) self.Eccentricity.setObjectName(_fromUtf8("Eccentricity")) self.kurtosis = QtGui.QLineEdit(Form) self.kurtosis.setGeometry(QtCore.QRect(150, 420, 51, 24)) self.kurtosis.setObjectName(_fromUtf8("kurtosis")) self.Skew = QtGui.QLineEdit(Form) self.Skew.setGeometry(QtCore.QRect(150, 480, 113, 24)) self.Skew.setObjectName(_fromUtf8("Skew")) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(50, 390, 91, 20)) self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(50, 420, 91, 20)) self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_2.setObjectName(_fromUtf8("label_2")) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(50, 450, 91, 20)) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(_fromUtf8("label_3")) self.label_4 = QtGui.QLabel(Form) self.label_4.setGeometry(QtCore.QRect(50, 480, 91, 20)) self.label_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_4.setObjectName(_fromUtf8("label_4")) self.label_5 = QtGui.QLabel(Form) self.label_5.setGeometry(QtCore.QRect(50, 550, 91, 20)) self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_5.setObjectName(_fromUtf8("label_5")) self.label_6 = QtGui.QLabel(Form) self.label_6.setGeometry(QtCore.QRect(50, 670, 91, 20)) self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_6.setObjectName(_fromUtf8("label_6")) self.LoadImage = QtGui.QPushButton(Form) self.LoadImage.setGeometry(QtCore.QRect(220, 50, 89, 27)) self.LoadImage.setObjectName(_fromUtf8("LoadImage")) self.label_7 = QtGui.QLabel(Form) self.label_7.setGeometry(QtCore.QRect(340, 50, 301, 20)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setWeight(75) self.label_7.setFont(font) self.label_7.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_7.setObjectName(_fromUtf8("label_7")) self.refresh = QtGui.QPushButton(Form) self.refresh.setGeometry(QtCore.QRect(600, 390, 89, 27)) self.refresh.setObjectName(_fromUtf8("refresh")) self.label_8 = QtGui.QLabel(Form) self.label_8.setGeometry(QtCore.QRect(560, 470, 91, 20)) self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_8.setObjectName(_fromUtf8("label_8")) self.label_9 = QtGui.QLabel(Form) self.label_9.setGeometry(QtCore.QRect(560, 540, 91, 20)) self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_9.setObjectName(_fromUtf8("label_9")) self.realLabel = QtGui.QLineEdit(Form) self.realLabel.setGeometry(QtCore.QRect(660, 460, 71, 51)) font = QtGui.QFont() font.setPointSize(20) self.realLabel.setFont(font) self.realLabel.setReadOnly(True) self.realLabel.setObjectName(_fromUtf8("realLabel")) self.PreductedLabel = QtGui.QLineEdit(Form) self.PreductedLabel.setGeometry(QtCore.QRect(660, 530, 71, 51)) font = QtGui.QFont() font.setPointSize(20) self.PreductedLabel.setFont(font) self.PreductedLabel.setReadOnly(True) self.PreductedLabel.setObjectName(_fromUtf8("PreductedLabel")) self.label_10 = QtGui.QLabel(Form) self.label_10.setGeometry(QtCore.QRect(580, 720, 201, 20)) self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_10.setObjectName(_fromUtf8("label_10")) self.LogoUN = QtGui.QLabel(Form) self.LogoUN.setGeometry(QtCore.QRect(580, 610, 201, 91)) self.LogoUN.setText(_fromUtf8("")) self.LogoUN.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.LogoUN.setObjectName(_fromUtf8("LogoUN")) self.CenterMass_2 = QtGui.QLineEdit(Form) self.CenterMass_2.setGeometry(QtCore.QRect(210, 390, 51, 24)) self.CenterMass_2.setObjectName(_fromUtf8("CenterMass_2")) self.kurtosis_2 = QtGui.QLineEdit(Form) self.kurtosis_2.setGeometry(QtCore.QRect(210, 420, 51, 24)) self.kurtosis_2.setObjectName(_fromUtf8("kurtosis_2")) self.label_11 = QtGui.QLabel(Form) self.label_11.setGeometry(QtCore.QRect(160, 370, 21, 20)) self.label_11.setAlignment(QtCore.Qt.AlignCenter) self.label_11.setObjectName(_fromUtf8("label_11")) self.label_12 = QtGui.QLabel(Form) self.label_12.setGeometry(QtCore.QRect(220, 370, 21, 20)) self.label_12.setAlignment(QtCore.Qt.AlignCenter) self.label_12.setObjectName(_fromUtf8("label_12")) self.signature = QtGui.QLabel(Form) self.signature.setGeometry(QtCore.QRect(100, 110, 291, 251)) self.signature.setAutoFillBackground(True) self.signature.setText(_fromUtf8("")) self.signature.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.signature.setObjectName(_fromUtf8("signature")) self.featureSignature = QtGui.QLabel(Form) self.featureSignature.setGeometry(QtCore.QRect(450, 120, 291, 251)) self.featureSignature.setAutoFillBackground(True) self.featureSignature.setText(_fromUtf8("")) self.featureSignature.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.featureSignature.setObjectName(_fromUtf8("featureSignature")) self.Presure = QtGui.QTableWidget(Form) self.Presure.setGeometry(QtCore.QRect(150, 510, 231, 121)) self.Presure.setObjectName(_fromUtf8("Presure")) self.Presure.setColumnCount(0) self.Presure.setRowCount(0) self.Gradient = QtGui.QTableWidget(Form) self.Gradient.setGeometry(QtCore.QRect(150, 640, 331, 101)) self.Gradient.setObjectName(_fromUtf8("Gradient")) self.Gradient.setColumnCount(0) self.Gradient.setRowCount(0) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) ############################################ # Universidad Nacional de Colombia LOGO ############################################ logoPic = QPixmap(os.getcwd() +'/LogoUNAL.png') self.LogoUN.setPixmap(logoPic.scaled(191,101,Qt.KeepAspectRatio)) self.LogoUN.show() # load image self.LoadImage.clicked.connect(lambda: self.loadImage()) self.realLabelText = -1 self.predicted = -1 # Predict Image self.refresh.clicked.connect(lambda: self.predicLabel())
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect, myname): global xscale, yscale self.myname = myname self.rect = rect self.satellite = Config.satellite try: if radar["satellite"]: self.satellite = 1 except KeyError: pass self.baseurl = self.mapurl(radar, rect, False) print "google map base url: " + self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) print "radar url: " + self.wxurl QtGui.QLabel.__init__(self, parent) self.interval = Config.radar_refresh * 60 self.lastwx = 0 self.retries = 0 self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie() def mapurl(self, radar, rect, markersonly): # 'https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er='+rcenter.lat+','+rcenter.lng+'&zoom='+rzoom+'&size=300x275'+markersr; urlp = [] if len(ApiKeys.googleapi) > 0: urlp.append('key=' + ApiKeys.googleapi) urlp.append('center=' + str(radar['center'].lat) + ',' + str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width() / 2, rsize.height() / 2) zoom -= 1 urlp.append('zoom=' + str(zoom)) urlp.append('size=' + str(rsize.width()) + 'x' + str(rsize.height())) if markersonly: urlp.append('style=visibility:off') else: urlp.append('maptype=hybrid') for marker in radar['markers']: marks = [] for opts in marker: if opts != 'location': marks.append(opts + ':' + marker[opts]) marks.append( str(marker['location'].lat) + ',' + str(marker['location'].lng)) urlp.append('markers=' + '|'.join(marks)) return 'http://maps.googleapis.com/maps/api/staticmap?' + \ '&'.join(urlp) def radarurl(self, radar, rect): # wuprefix = 'http://api.wunderground.com/api/'; # wuprefix+wuapi+'/animatedradar/image.gif?maxlat='+rNE.lat+'&maxlon='+ # rNE.lng+'&minlat='+rSW.lat+'&minlon='+rSW.lng+wuoptionsr; # wuoptionsr = '&width=300&height=275&newmaps=0&reproj.automerc=1&num=5 # &delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1'; rr = getCorners(radar['center'], radar['zoom'], rect.width(), rect.height()) if self.satellite: return (Config.wuprefix + ApiKeys.wuapi + '/animatedsatellite/lang:' + Config.wuLanguage + '/image.gif' + '?maxlat=' + str(rr['N']) + '&maxlon=' + str(rr['E']) + '&minlat=' + str(rr['S']) + '&minlon=' + str(rr['W']) + '&width=' + str(rect.width()) + '&height=' + str(rect.height()) + '&newmaps=0&reproj.automerc=1&num=5&delay=25' + '&timelabel=1&timelabel.y=10&smooth=1&key=sat_ir4_bottom') else: return (Config.wuprefix + ApiKeys.wuapi + '/animatedradar/lang:' + Config.wuLanguage + '/image.gif' + '?maxlat=' + str(rr['N']) + '&maxlon=' + str(rr['E']) + '&minlat=' + str(rr['S']) + '&minlon=' + str(rr['W']) + '&width=' + str(rect.width()) + '&height=' + str(rect.height()) + '&newmaps=0&reproj.automerc=1&num=5&delay=25' + '&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1' + '&radar_bitmap=1&xnoclutter=1&xnoclutter_mask=1&cors=1') def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) if self.satellite: p = QPixmap(self.basepixmap.size()) p.fill(Qt.transparent) painter = QPainter() painter.begin(p) painter.setOpacity(0.6) painter.drawPixmap(0, 0, self.basepixmap) painter.end() self.basepixmap = p self.wwx.setPixmap(self.basepixmap) else: self.setPixmap(self.basepixmap) def mkfinished(self): if self.mkreply.error() != QNetworkReply.NoError: return self.mkpixmap = QPixmap() self.mkpixmap.loadFromData(self.mkreply.readAll()) if self.mkpixmap.size() != self.rect.size(): self.mkpixmap = self.mkpixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) br = QBrush(QColor(Config.dimcolor)) painter = QPainter() painter.begin(self.mkpixmap) painter.fillRect(0, 0, self.mkpixmap.width(), self.mkpixmap.height(), br) painter.end() self.wmk.setPixmap(self.mkpixmap) def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: print "get radar error " + self.myname + ":" + \ str(self.wxreply.error()) self.lastwx = 0 return print "radar map received:" + self.myname + ":" + time.ctime() self.wxmovie.stop() self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) mov = QMovie(self.wxbuff, 'GIF') print "radar map frame count:" + self.myname + ":" + \ str(mov.frameCount()) + ":r" + str(self.retries) if mov.frameCount() > 2: self.lastwx = time.time() self.retries = 0 else: # radar image retreval failed if self.retries > 3: # give up, last successful animation stays. # the next normal radar_refresh time (default 10min) will apply self.lastwx = time.time() return self.lastwx = 0 # count retries self.retries = self.retries + 1 # retry in 5 seconds QtCore.QTimer.singleShot(5 * 1000, self.getwx) return self.wxmovie = mov if self.satellite: self.setMovie(self.wxmovie) else: self.wwx.setMovie(self.wxmovie) if self.parent().isVisible(): self.wxmovie.start() def getwx(self): global lastapiget i = 0.1 # making sure there is at least 2 seconds between radar api calls lastapiget += 2 if time.time() > lastapiget: lastapiget = time.time() else: i = lastapiget - time.time() print "get radar api call spacing oneshot get i=" + str(i) QtCore.QTimer.singleShot(i * 1000, self.getwx2) def getwx2(self): global manager try: if self.wxreply.isRunning(): return except Exception: pass print "getting radar map " + self.myname + ":" + time.ctime() self.wxreq = QNetworkRequest( QUrl(self.wxurl + '&rrrand=' + str(time.time()))) self.wxreply = manager.get(self.wxreq) QtCore.QObject.connect(self.wxreply, QtCore.SIGNAL("finished()"), self.wxfinished) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply, QtCore.SIGNAL("finished()"), self.basefinished) def getmk(self): global manager self.mkreq = QNetworkRequest(QUrl(self.mkurl)) self.mkreply = manager.get(self.mkreq) QtCore.QObject.connect(self.mkreply, QtCore.SIGNAL("finished()"), self.mkfinished) def start(self, interval=0): if interval > 0: self.interval = interval self.getbase() self.getmk() self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.getwx) def wxstart(self): print "wxstart for " + self.myname if (self.lastwx == 0 or (self.lastwx + self.interval) < time.time()): self.getwx() # random 1 to 10 seconds added to refresh interval to spread the # queries over time i = (self.interval + random.uniform(1, 10)) * 1000 self.timer.start(i) self.wxmovie.start() QtCore.QTimer.singleShot(1000, self.wxmovie.start) def wxstop(self): print "wxstop for " + self.myname self.timer.stop() self.wxmovie.stop() def stop(self): try: self.timer.stop() self.timer = None if self.wxmovie: self.wxmovie.stop() except Exception: pass
class BackgroundFrame(QFrame): backgroundColor = QtDynamicProperty('backgroundColor', unicode) backgroundImage = QtDynamicProperty('backgroundImage', unicode) imageGeometry = QtDynamicProperty('imageGeometry', QRect) def __init__(self, parent=None): super(BackgroundFrame, self).__init__(parent) self.backgroundColor = None self.backgroundImage = None self.imageGeometry = None self.pixmap = None self.scaled_pixmap = None @property def image_position(self): return QPoint( 0, 0) if self.imageGeometry is None else self.imageGeometry.topLeft() @property def image_size(self): if self.imageGeometry is not None: size = self.imageGeometry.size().expandedTo(QSize( 0, 0)) # requested size with negative values turned to 0 if size.isNull(): return size if self.pixmap is None else self.pixmap.size() elif size.width() == 0: return size.expandedTo(QSize(16777215, 0)) elif size.height() == 0: return size.expandedTo(QSize(0, 16777215)) else: return size elif self.pixmap: return self.pixmap.size() else: return QSize(0, 0) def event(self, event): if event.type() == QEvent.DynamicPropertyChange: if event.propertyName() == 'backgroundImage': self.pixmap = QPixmap() if self.backgroundImage and self.pixmap.load( Resources.get(self.backgroundImage)): self.scaled_pixmap = self.pixmap.scaled( self.image_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) else: self.pixmap = self.scaled_pixmap = None self.update() elif event.propertyName() == 'imageGeometry' and self.pixmap: self.scaled_pixmap = self.pixmap.scaled( self.image_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.update() elif event.propertyName() == 'backgroundColor': self.update() return super(BackgroundFrame, self).event(event) def resizeEvent(self, event): self.scaled_pixmap = self.pixmap and self.pixmap.scaled( self.image_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) def paintEvent(self, event): super(BackgroundFrame, self).paintEvent(event) painter = QPainter(self) if self.backgroundColor: painter.fillRect(self.rect(), QColor(self.backgroundColor)) if self.scaled_pixmap is not None: painter.drawPixmap(self.image_position, self.scaled_pixmap) painter.end()
class Entity(QWidget): def __init__(self, base_image, parent=None): super().__init__(parent) self._base_label = QLabel(self) self._base_image = base_image self._decor_label = QLabel(self) self._decor_pixmap = None self.__pixmap = None """:type: PyQt4.QtGui.QPixmap""" self.__cord_x = 0 self.__cord_y = 0 self.__angle = 0 self.setAlignment(Qt.AlignCenter) self.updatePixmap() if _debugging: self.setStyleSheet("border: 1px solid black") @property def angle(self): return self.__angle @angle.setter def angle(self, angle): self.__angle = angle self.updatePixmap() @property def cord_x(self): return self.__cord_x @cord_x.setter def cord_x(self, cord): self.__cord_x = cord self.move(self.cord_x, self.cord_y) @property def cord_y(self): return self.__cord_y @cord_y.setter def cord_y(self, cord): self.__cord_y = cord self.move(self.cord_x, self.cord_y) def add_decoration(self, path): if path is None: self._decor_label.hide() else: self._decor_label = QLabel(self) self._decor_pixmap = QPixmap(path) self._decor_pixmap = self._decor_pixmap.scaled( self._decor_pixmap.width() * _SCALE, self._decor_pixmap.height() * _SCALE) self._decor_pixmap = self._decor_pixmap.transformed( QTransform().rotate(self.angle)) self._decor_label.setPixmap(self._decor_pixmap) def updatePixmap(self): path = _PATH + os.sep + "assets" + os.sep + self._base_image self.__pixmap = QPixmap(path) self.__pixmap = self.__pixmap.scaled(self.__pixmap.width() * _SCALE, self.__pixmap.height() * _SCALE) self.__pixmap = self.__pixmap.transformed(QTransform().rotate( self.angle)) self._base_label.setPixmap(self.__pixmap) self.setFixedSize(self.__pixmap.width(), self.__pixmap.height()) def setFixedSize(self, x, y): super().setFixedSize(x, y) self._base_label.setFixedSize(x, y) def setAlignment(self, alignment): self._base_label.setAlignment(alignment) self._decor_label.setAlignment(alignment)
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect, myname): global xscale, yscale self.myname = myname self.rect = rect self.anim = 5 self.zoom = radar["zoom"] self.point = radar["center"] self.radar = radar self.baseurl = self.mapurl(radar, rect) print "map base url: " + self.baseurl QtGui.QLabel.__init__(self, parent) self.interval = Config.radar_refresh * 60 self.lastwx = 0 self.retries = 0 self.corners = getCorners(self.point, self.zoom, rect.width(), rect.height()) self.baseTime = 0 self.cornerTiles = { "NW": getTileXY(LatLng(self.corners["N"], self.corners["W"]), self.zoom), "NE": getTileXY(LatLng(self.corners["N"], self.corners["E"]), self.zoom), "SE": getTileXY(LatLng(self.corners["S"], self.corners["E"]), self.zoom), "SW": getTileXY(LatLng(self.corners["S"], self.corners["W"]), self.zoom) } self.tiles = [] self.tiletails = [] self.totalWidth = 0 self.totalHeight = 0 self.tilesWidth = 0 self.tilesHeight = 0 self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) for y in range(int(self.cornerTiles["NW"]["Y"]), int(self.cornerTiles["SW"]["Y"]) + 1): self.totalHeight += 256 self.tilesHeight += 1 for x in range(int(self.cornerTiles["NW"]["X"]), int(self.cornerTiles["NE"]["X"]) + 1): tile = {"X": x, "Y": y} self.tiles.append(tile) tail = "/256/%d/%d/%d.png?color=3" % (self.zoom, x, y) self.tiletails.append(tail) for x in range(int(self.cornerTiles["NW"]["X"]), int(self.cornerTiles["NE"]["X"]) + 1): self.totalWidth += 256 self.tilesWidth += 1 self.frameImages = [] self.frameIndex = 0 self.displayedFrame = 0 self.ticker = 0 self.lastget = 0 def rtick(self): if time.time() > (self.lastget + self.interval): self.get(time.time()) self.lastget = time.time() if len(self.frameImages) < 1: return if self.displayedFrame == 0: self.ticker += 1 if self.ticker < 5: return self.ticker = 0 f = self.frameImages[self.displayedFrame] self.wwx.setPixmap(f["image"]) self.displayedFrame += 1 if self.displayedFrame >= len(self.frameImages): self.displayedFrame = 0 def get(self, t=0): t = int(t / 600) * 600 if t > 0 and self.baseTime == t: return if t == 0: t = self.baseTime else: self.baseTime = t newf = [] for f in self.frameImages: if f["time"] >= (t - self.anim * 600): newf.append(f) self.frameImages = newf firstt = t - self.anim * 600 for tt in range(firstt, t + 1, 600): print "get... " + str(tt) + " " + self.myname gotit = False for f in self.frameImages: if f["time"] == tt: gotit = True if not gotit: self.getTiles(tt) break def getTiles(self, t, i=0): t = int(t / 600) * 600 self.getTime = t self.getIndex = i if i == 0: self.tileurls = [] self.tileQimages = [] for tt in self.tiletails: tileurl = "https://tilecache.rainviewer.com/v2/radar/%d/%s" \ % (t, tt) self.tileurls.append(tileurl) print self.myname + " " + str(self.getIndex) + " " + self.tileurls[i] self.tilereq = QNetworkRequest(QUrl(self.tileurls[i])) self.tilereply = manager.get(self.tilereq) QtCore.QObject.connect(self.tilereply, QtCore.SIGNAL("finished()"), self.getTilesReply) def getTilesReply(self): print "getTilesReply " + str(self.getIndex) if self.tilereply.error() != QNetworkReply.NoError: return self.tileQimages.append(QImage()) self.tileQimages[self.getIndex].loadFromData(self.tilereply.readAll()) self.getIndex = self.getIndex + 1 if self.getIndex < len(self.tileurls): self.getTiles(self.getTime, self.getIndex) else: self.combineTiles() self.get() def combineTiles(self): global radar1 ii = QImage(self.tilesWidth * 256, self.tilesHeight * 256, QImage.Format_ARGB32) painter = QPainter() painter.begin(ii) painter.setPen(QColor(255, 255, 255, 255)) painter.setFont(QFont("Arial", 10)) i = 0 xo = self.cornerTiles["NW"]["X"] xo = int((int(xo) - xo) * 256) yo = self.cornerTiles["NW"]["Y"] yo = int((int(yo) - yo) * 256) for y in range(0, self.totalHeight, 256): for x in range(0, self.totalWidth, 256): painter.drawImage(x, y, self.tileQimages[i]) # painter.drawRect(x, y, 255, 255) # painter.drawText(x+3, y+12, self.tiletails[i]) i += 1 painter.end() painter = None self.tileQimages = [] ii2 = ii.copy(-xo, -yo, self.rect.width(), self.rect.height()) ii = None painter2 = QPainter() painter2.begin(ii2) timestamp = "{0:%H:%M} RainView.com".format( datetime.datetime.fromtimestamp(self.getTime)) painter2.setPen(QColor(63, 63, 63, 255)) painter2.setFont(QFont("Arial", 8)) painter2.setRenderHint(QPainter.TextAntialiasing) painter2.drawText(3 - 1, 12 - 1, timestamp) painter2.drawText(3 + 2, 12 + 1, timestamp) painter2.setPen(QColor(255, 255, 255, 255)) painter2.drawText(3, 12, timestamp) painter2.drawText(3 + 1, 12, timestamp) painter2.end() painter2 = None ii3 = QPixmap(ii2) ii2 = None self.frameImages.append({"time": self.getTime, "image": ii3}) ii3 = None def mapurl(self, radar, rect): mb = 0 try: mb = Config.usemapbox except: pass if mb: return self.mapboxurl(radar, rect) else: return self.googlemapurl(radar, rect) def mapboxurl(self, radar, rect): # note we're using google maps zoom factor. # Mapbox equivilant zoom is one less # They seem to be using 512x512 tiles instead of 256x256 style = 'mapbox/satellite-streets-v10' if 'style' in radar: style = radar['style'] return 'https://api.mapbox.com/styles/v1/' + \ style + \ '/static/' + \ str(radar['center'].lng) + ',' + \ str(radar['center'].lat) + ',' + \ str(radar['zoom']-1) + ',0,0/' + \ str(rect.width()) + 'x' + str(rect.height()) + \ '?access_token=' + ApiKeys.mbapi def googlemapurl(self, radar, rect): urlp = [] if len(ApiKeys.googleapi) > 0: urlp.append('key=' + ApiKeys.googleapi) urlp.append('center=' + str(radar['center'].lat) + ',' + str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width() / 2, rsize.height() / 2) zoom -= 1 urlp.append('zoom=' + str(zoom)) urlp.append('size=' + str(rsize.width()) + 'x' + str(rsize.height())) urlp.append('maptype=hybrid') return 'http://maps.googleapis.com/maps/api/staticmap?' + \ '&'.join(urlp) def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) # make marker pixmap self.mkpixmap = QPixmap(self.basepixmap.size()) self.mkpixmap.fill(Qt.transparent) br = QBrush(QColor(Config.dimcolor)) painter = QPainter() painter.begin(self.mkpixmap) painter.fillRect(0, 0, self.mkpixmap.width(), self.mkpixmap.height(), br) for marker in self.radar['markers']: pt = getPoint(marker["location"], self.point, self.zoom, self.rect.width(), self.rect.height()) mk2 = QImage() mkfile = 'teardrop' if 'image' in marker: mkfile = marker['image'] if os.path.dirname(mkfile) == '': mkfile = os.path.join('markers', mkfile) if os.path.splitext(mkfile)[1] == '': mkfile += '.png' mk2.load(mkfile) if mk2.format != QImage.Format_ARGB32: mk2 = mk2.convertToFormat(QImage.Format_ARGB32) mkh = 80 # self.rect.height() / 5 if 'size' in marker: if marker['size'] == 'small': mkh = 64 if marker['size'] == 'mid': mkh = 70 if marker['size'] == 'tiny': mkh = 40 if 'color' in marker: c = QColor(marker['color']) (cr, cg, cb, ca) = c.getRgbF() for x in range(0, mk2.width()): for y in range(0, mk2.height()): (r, g, b, a) = QColor.fromRgba(mk2.pixel(x, y)).getRgbF() r = r * cr g = g * cg b = b * cb mk2.setPixel(x, y, QColor.fromRgbF(r, g, b, a).rgba()) mk2 = mk2.scaledToHeight(mkh, 1) painter.drawImage(pt.x - mkh / 2, pt.y - mkh / 2, mk2) painter.end() self.wmk.setPixmap(self.mkpixmap) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply, QtCore.SIGNAL("finished()"), self.basefinished) def start(self, interval=0): if interval > 0: self.interval = interval self.getbase() self.timer = QtCore.QTimer() self.timer.timeout.connect(self.rtick) self.lastget = time.time() - self.interval + random.uniform(3, 10) def wxstart(self): print "wxstart for " + self.myname self.timer.start(200) def wxstop(self): print "wxstop for " + self.myname self.timer.stop() def stop(self): try: self.timer.stop() self.timer = None except Exception: pass
def __init__(self, parent=None): super(MyQtApp, self).__init__(parent) self.setup6(self) # self.showMaximized() self.setWindowTitle("Proses Digital Signature") self.btn_ok.clicked.connect(self.select_nilair) self.btn_next.clicked.connect(self.next) button = self.btn_next button.setIcon(QtGui.QIcon("images/next-arrow.png")) button.setIconSize(QtCore.QSize(35, 35)) label = self.label_pic label2 = self.label_pic_2 label3 = self.label_pic_3 label4 = self.label_pic_4 label5 = self.label_pic_5 label6 = self.label_pic_6 label7 = self.label_pic_7 label11 = self.label_pic_11 label12 = self.label_pic_12 label13 = self.label_pic_13 label16 = self.label_pic_16 image = QPixmap("images/down-arrow.png") label.setPixmap(image.scaled(25, 25)) label2.setPixmap(image.scaled(25, 25)) label3.setPixmap(image.scaled(25, 25)) label4.setPixmap(image.scaled(25, 25)) label5.setPixmap(image.scaled(25, 25)) label6.setPixmap(image.scaled(25, 25)) label7.setPixmap(image.scaled(25, 25)) label11.setPixmap(image.scaled(25, 25)) label12.setPixmap(image.scaled(25, 25)) label13.setPixmap(image.scaled(25, 25)) label16.setPixmap(image.scaled(25, 25)) label_fungsi = self.label_hash label_fungsi.setText(open('output/fungsihash.txt', 'r').read()) label_nilai = self.label_nilaihash label_nilai.setText("H(M)") label_nilaiprima = self.label_nilaip label_nilaiprima.setText("p = " + open('output/nilaip.txt', 'r').read()[0:3] + "..") label_L = self.label_nilaiL label_L.setText("L = " + open('output/nilaiL.txt', 'r').read()) label_nilaipembagi = self.label_nilaiq label_nilaipembagi.setText( "q = " + open('output/nilaipembagiutama.txt', 'r').read()[0:3] + "..") label_x = self.label_nilaix label_x.setText("x = " + open('output/nilaix.txt', 'r').read()[0:3] + "..") label_k = self.label_nilaik label_k.setText("k = " + open('output/nilaik.txt', 'r').read()[0:3] + "..") label_h = self.label_nilaih label_h.setText("h = " + open('output/nilaih.txt', 'r').read()[0:3] + "..") label_g = self.label_nilaig label_g.setText("g = " + open('output/nilaig.txt', 'r').read()[0:3] + "..")
def display_image(self, imagepath): pix = QPixmap(imagepath) self.image_label.setPixmap( pix.scaled(self.display.size(), Qt.KeepAspectRatioByExpanding))
def loadImage(self): bashCommand = "rm test.PNG" import subprocess process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) output, error = process.communicate() print output # first of all, the base transformation of the data points is needed base = plt.gca().transData rot = transforms.Affine2D().rotate_deg(270) filename = askopenfilename() img = rz.resizeSignature(filename) # Image filtering imgSmooted = GaussS.gaussianBlur(1, 0.5, img) imgFiltered = bN.filter(imgSmooted) # Calculate the ones in the matrix. blackPoints = bN.calculateBlackPoints(imgFiltered) # Calculate the center of mass centerMass = bN.centroid(blackPoints) self.CenterMass.setText(str(centerMass[1])) self.CenterMass_2.setText(str(centerMass[0])) # Calculate the eccentricity eccentricity = bN.calculateEccentricity(blackPoints) self.Eccentricity.setText(str(round(eccentricity,4))) # Calculate the representative points of a signature densePoints = bN.calculateDensePoints(blackPoints) listY = [y[0] for y in blackPoints] listX = [x[1] for x in blackPoints] plt.plot(listY, listX, "ro", transform=rot + base) # Print Center of mass plt.plot(centerMass[0], centerMass[1], "^", transform=rot + base) # Print dense points densePoints = densePoints.T plt.plot(densePoints[0], densePoints[1], "g+", transform=rot + base) kurtosis = bN.calculateKurtosis(blackPoints) self.kurtosis.setText(str(round(kurtosis[1], 4 ))) self.kurtosis_2.setText(str(round(kurtosis[0], 4))) # Print skew detection testSkew = bN.skewDetection(imgFiltered) self.Skew.setText(str(round(testSkew))) # Calculate gradient in a grid 4x4 - Choosen just 2x2 important grid in the middle matrixGradient = bN.calculateGradient(blackPoints, imgFiltered.shape) self.Gradient.setRowCount(len(matrixGradient)) self.Gradient.setColumnCount(len(matrixGradient[0])) for i, row in enumerate(matrixGradient): for j, val in enumerate(row): self.Gradient.setItem(i, j, QtGui.QTableWidgetItem(str(val))) self.Gradient.resizeColumnsToContents() self.Gradient.resizeRowsToContents() # Calculate pressure in a grid 4x4 matrixPresure = np.around(bN.calculatePressure(imgSmooted), decimals=2) self.Presure.setRowCount(len(matrixPresure)) self.Presure.setColumnCount(len(matrixPresure[0])) for i, row in enumerate(matrixPresure): for j, val in enumerate(row): self.Presure.setItem(i, j, QtGui.QTableWidgetItem(str(val))) self.Presure.resizeColumnsToContents() self.Presure.resizeRowsToContents() plt.axis('off') # Plot Ellipse subplot = plt.subplot() b, a = drawEllipse(blackPoints) ell = Ellipse((centerMass[1], centerMass[0] * -1), b + 10, a + 10, edgecolor='black', facecolor='none', linewidth=5) subplot.add_patch(ell) # plt.plot([y positions of the points], [x positions of the points]) # plt.plot([testSkewLeft[1], testSkewRight[1]], [testSkewLeft[0], testSkewRight[0]], 'k') # plt.plot([testSkewLeft[1], testSkewLeft[1]], [testSkewLeft[0], testSkewRight[0]], 'k') # Save Scanned Signature plt.savefig("test.PNG", dpi=700) plt.close() ############################################ # Signature image ############################################ logoPic1 = QPixmap(filename) self.signature.setPixmap(logoPic1.scaled(291,255,Qt.KeepAspectRatio)) self.signature.show() ############################################ # Signature Feature ############################################ search_pixmap = QtGui.QPixmap() search_pixmap.load('test.PNG') self.featureSignature.setPixmap(search_pixmap.scaled(291, 255, Qt.KeepAspectRatio)) self.featureSignature.show() ######################## # Save test image ########################## vectorFeature = [] vectorFeature.append(round(centerMass[0], 4)) vectorFeature.append(round(centerMass[1], 4)) vectorFeature.append(round(eccentricity, 4)) vectorFeature.append(round(kurtosis[0], 4)) vectorFeature.append(round(kurtosis[1], 4)) vectorFeature.append(round(matrixGradient[0][0][0], 4)) vectorFeature.append(round(matrixGradient[0][0][1], 4)) vectorFeature.append(round(matrixGradient[0][1][0], 4)) vectorFeature.append(round(matrixGradient[0][1][1], 4)) vectorFeature.append(round(matrixGradient[0][2][0], 4)) vectorFeature.append(round(matrixGradient[0][2][1], 4)) vectorFeature.append(round(matrixGradient[0][3][0], 4)) vectorFeature.append(round(matrixGradient[0][3][1], 4)) vectorFeature.append(round(matrixGradient[1][0][0], 4)) vectorFeature.append(round(matrixGradient[1][0][1], 4)) vectorFeature.append(round(matrixGradient[1][1][0], 4)) vectorFeature.append(round(matrixGradient[1][1][1], 4)) vectorFeature.append(round(matrixGradient[1][2][0], 4)) vectorFeature.append(round(matrixGradient[1][2][1], 4)) vectorFeature.append(round(matrixGradient[1][3][0], 4)) vectorFeature.append(round(matrixGradient[1][3][1], 4)) vectorFeature.append(round(matrixPresure[0][0], 4)) vectorFeature.append(round(matrixPresure[0][1], 4)) vectorFeature.append(round(matrixPresure[0][2], 4)) vectorFeature.append(round(matrixPresure[0][3], 4)) vectorFeature.append(round(matrixPresure[1][0], 4)) vectorFeature.append(round(matrixPresure[1][1], 4)) vectorFeature.append(round(matrixPresure[1][2], 4)) vectorFeature.append(round(matrixPresure[1][3], 4)) vectorFeature.append(round(matrixPresure[2][0], 4)) vectorFeature.append(round(matrixPresure[2][1], 4)) vectorFeature.append(round(matrixPresure[2][2], 4)) vectorFeature.append(round(matrixPresure[2][3], 4)) vectorFeature.append(round(matrixPresure[3][0], 4)) vectorFeature.append(round(matrixPresure[3][1], 4)) vectorFeature.append(round( matrixPresure[3][2], 4)) vectorFeature.append(round(matrixPresure[3][3], 4)) label = 0 if len(filename.split('/')[len(filename.split('/'))-1]) < 11: label = int(filename.split('/')[len(filename.split('/'))-2]) # print label matrixData = [] vectorTarget = [] with open('../LearningInformation/learningBayesianMulticlassGenuine.csv') as f: readerGenuine = csv.reader(f) readerGenuine.next() for i in readerGenuine: matrixData.append(map(float, i[:len(i) - 1])) # matrixData.append(map(float, i[2:5] + i[25:len(i) - 1])) vectorTarget.append(int(i[len(i) - 1])) with open('../LearningInformation/learningBayesianMulticlassForgeries.csv') as f: readerForgeriestmp = csv.reader(f) readerForgeriestmp.next() for i in readerForgeriestmp: matrixData.append(map(float, i[:len(i) - 1])) # matrixData.append(map(float, i[2:5] + i[25:len(i) - 1])) vectorTarget.append(int(i[len(i) - 1])) matrixData = np.array(matrixData) vectorTarget = np.array(vectorTarget) asdsada = TemplateClassifier().fit(matrixData, vectorTarget) y_predict_X = asdsada.predict(vectorFeature)[0] self.realLabelText = label self.predicted = y_predict_X
class Entity(QWidget): def __init__(self, base_image, size, hp=100, pos=(0, 0), parent=None): super().__init__(parent) self._base_label = QLabel(self) self._base_image = base_image self._size = size self._decor_label = None self._decor_pixmap = None self._hp_max = hp self.__pixmap = None """:type: PyQt4.QtGui.QPixmap""" self.__cord_x = pos[0] self.__cord_y = pos[1] self.__angle = 0 self.__hp_bar = QProgressBar(self) self.__hp_bar.setMaximum(self._hp_max) self.__hp_bar.setValue(self._hp_max) self.__hp_bar.setTextVisible(False) self.__hp_bar.setMaximumSize(size[0], 5) self.setAlignment(Qt.AlignCenter) self.updatePixmap() if _debugging: self.setStyleSheet("border: 1px solid black") @property def health(self): return self.__hp_bar.value() @health.setter def health(self, hp): if hp > self._hp_max: hp = self._hp_max elif hp < 0: hp = 0 self.__hp_bar.setValue(hp) @property def angle(self): return self.__angle @angle.setter def angle(self, angle): self.__angle = angle self.updatePixmap() @property def cord_x(self): return self.__cord_x @cord_x.setter def cord_x(self, cord): self.__cord_x = cord self.move(self.cord_x, self.cord_y) @property def cord_y(self): return self.__cord_y @cord_y.setter def cord_y(self, cord): self.__cord_y = cord self.move(self.cord_x, self.cord_y) def hide_hp_bar(self, bool=False): if bool: self.__hp_bar.hide() else: self.__hp_bar.show() def add_decoration(self, path): if path is None: self._decor_label.deleteLater() self._decor_label = None else: self._decor_label = QLabel(self) self._decor_pixmap = QPixmap(path) # self._decor_pixmap = self._decor_pixmap.scaled(self._size[0], self._size[1]) self._decor_pixmap = self._decor_pixmap.transformed( QTransform().rotate(self.angle)) self._decor_label.setPixmap(self._decor_pixmap) self._decor_label.setAlignment(Qt.AlignCenter) self._decor_label.show() def updatePixmap(self): path = get_asset_path(self._base_image) self.__pixmap = QPixmap(path) self.__pixmap = self.__pixmap.scaled(self._size[0], self._size[1]) self.__pixmap = self.__pixmap.transformed(QTransform().rotate( self.angle)) self._base_label.setPixmap(self.__pixmap) self._base_label.show() # self.setFixedSize(self.__pixmap.width(), self.__pixmap.height()) def setFixedSize(self, x, y): super().setFixedSize(x, y) self._base_label.setFixedSize(x, y) def setAlignment(self, alignment): self._base_label.setAlignment(alignment)
def cursor(name): pix = QPixmap(name) pix = pix.scaled(QSize(24, 24)) return QCursor(pix)
class DetailsDialog(DetailsDialogBase): def __init__(self, parent, app): DetailsDialogBase.__init__(self, parent, app) self.selectedPixmap = None self.referencePixmap = None def _setupUi(self): self.setWindowTitle(tr("Details")) self.resize(502, 295) self.setMinimumSize(QSize(250, 250)) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(0) self.verticalLayout.setMargin(0) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setSpacing(4) self.selectedImage = QLabel(self) sizePolicy = QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.selectedImage.sizePolicy().hasHeightForWidth()) self.selectedImage.setSizePolicy(sizePolicy) self.selectedImage.setScaledContents(False) self.selectedImage.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.selectedImage) self.referenceImage = QLabel(self) sizePolicy = QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.referenceImage.sizePolicy().hasHeightForWidth()) self.referenceImage.setSizePolicy(sizePolicy) self.referenceImage.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.referenceImage) self.verticalLayout.addLayout(self.horizontalLayout) self.tableView = DetailsTable(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableView.sizePolicy().hasHeightForWidth()) self.tableView.setSizePolicy(sizePolicy) self.tableView.setMinimumSize(QSize(0, 188)) self.tableView.setMaximumSize(QSize(16777215, 190)) self.tableView.setAlternatingRowColors(True) self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableView.setShowGrid(False) self.verticalLayout.addWidget(self.tableView) def _update(self): if not self.app.model.selected_dupes: return dupe = self.app.model.selected_dupes[0] group = self.app.model.results.get_group_of_duplicate(dupe) ref = group.ref self.selectedPixmap = QPixmap(str(dupe.path)) if ref is dupe: self.referencePixmap = None else: self.referencePixmap = QPixmap(str(ref.path)) self._updateImages() def _updateImages(self): if self.selectedPixmap is not None: target_size = self.selectedImage.size() scaledPixmap = self.selectedPixmap.scaled(target_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.selectedImage.setPixmap(scaledPixmap) else: self.selectedImage.setPixmap(QPixmap()) if self.referencePixmap is not None: target_size = self.referenceImage.size() scaledPixmap = self.referencePixmap.scaled(target_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.referenceImage.setPixmap(scaledPixmap) else: self.referenceImage.setPixmap(QPixmap()) #--- Override def resizeEvent(self, event): self._updateImages() def show(self): DetailsDialogBase.show(self) self._update() # model --> view def refresh(self): DetailsDialogBase.refresh(self) if self.isVisible(): self._update()
class PreviewQLabel(QLabel): """ QLabel subclass used to show a preview image. Properties: preview_window (PreviewWindow): preview window that contains this label scale_factor: (float): scale factor between label pixels & pixels of the actual image start_crop_coord (y, x): starting coordinate of mouse crop selection end_crop_coord (y, x): ending coordinate of mouse crop selection pixmap (Array): label's pixmap """ def __init__(self, preview_window): QLabel.__init__(self) self.preview_window = preview_window self.scale_factor = None self.pix = None # image label's pixmap self.pix_size = None # size of image label's pixmap self.image = None # accept clicks self.setAcceptDrops(True) def resizeEvent(self, event): if self.pix is not None: self.setPixmap( self.pix.scaled(self.width(), self.height(), Qt.KeepAspectRatio)) self.scale_factor = self.pixmap().height() / self.image.shape[0] def mousePressEvent(self, event): if self.scale_factor: self.click_start_coord = (int((event.y() / self.scale_factor)), int((event.x() / self.scale_factor))) self.prev_coord = self.click_start_coord def mouseMoveEvent(self, event): if self.scale_factor: self.click_end_coord = (int((event.y() / self.scale_factor)), int((event.x() / self.scale_factor))) if self.preview_window.selecting_crop: # draw colored crop selection self.preview_window.draw_crop_selection( self.click_start_coord, self.click_end_coord) else: self.preview_window.change_offset(self.prev_coord, self.click_end_coord) self.prev_coord = self.click_end_coord def mouseReleaseEvent(self, event): if self.scale_factor: self.click_end_coord = (int((event.y() / self.scale_factor)), int((event.x() / self.scale_factor))) print("User clicked {}.".format(self.click_end_coord)) if self.click_end_coord != self.click_start_coord: # finished selecting crop area; crop the image self.preview_window.crop_selection(self.click_start_coord, self.click_end_coord) else: # draw tail start coordinate self.preview_window.remove_tail_start() self.preview_window.draw_tail_start( np.array(self.click_end_coord)) def update_pixmap(self, image, new_load=False, zoom=1): if image is None: self.scale_factor = None self.pix = None # image label's pixmap self.pix_size = None # size of image label's pixmap self.clear() else: # get image info height, width, bytesPerComponent = image.shape bytesPerLine = bytesPerComponent * width # create qimage qimage = QImage(image.data, image.shape[1], image.shape[0], bytesPerLine, QImage.Format_RGB888) qimage.setColorTable(gray_color_table) # generate pixmap self.pix = QPixmap(qimage) self.setPixmap( self.pix.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.FastTransformation)) self.scale_factor = self.pixmap().height() / image.shape[0] self.image = image
def __setDefaultValue(self): logo1 = QPixmap("icons/car.png") logo1=logo1.scaled(64, 64, QtCore.Qt.KeepAspectRatio) self.logo_1_u.setPixmap(logo1) self.logo_1_u.show() logo2 = QPixmap("icons/signal.png") logo2=logo2.scaled(32, 32, QtCore.Qt.KeepAspectRatio) self.logo_2_u.setPixmap(logo2) self.logo_2_u.show() # default VIN , from the seqence 1 self.vin_u.setText("1") # default prefix of VIN ,length is 13 characters self.vin_prefix_u.setText("PLV0000000000") # enable VIN prefix by default self.use_vin_prefix_u.setChecked(True) # set thread number to 1 by default self.thread_number_u.setText("1") # set CAN message interval time to 100ms self.can_1_interval_u.setText("10") self.can_2_interval_u.setText("10") #set A/D interval time to 100ms self.ad_1_interval_u.setText("10") self.ad_2_interval_u.setText("10") #set Alg options self.alg_options = ["Sin", "Step","Triangle", "Random"] self.can_1_sig_1_alg_u.addItems(self.alg_options) self.can_1_sig_2_alg_u.addItems(self.alg_options) self.can_1_sig_3_alg_u.addItems(["Triangle"]) self.can_2_sig_1_alg_u.addItems(["Step"]) self.can_2_sig_2_alg_u.addItems(["Step"]) self.can_2_sig_3_alg_u.addItems(["Step"]) self.ad_1_alg_u.addItems(self.alg_options) self.ad_2_alg_u.addItems(self.alg_options) #Set CAN message 1 ABS_ESC_1 (0x92) DLC=8 CycleTime=20ms self.can_1_enable_u.setChecked(True) self.can_1_enable_u.setText("ABS_ESC_1 (0x92/146D)") # Unit=rpm StartBits=12 length=16 ByteOrder=Intel Offset=0 Factor=0.0625 Min=0 Max=4095.81 valueType=unsigned self.can_1_sig_1_name_u.setText("WheelSpeed_FL") # Unit=rpm StartBits=28 length=16 ByteOrder=Intel Offset=0 Factor=0.0625 Min=0 Max=4095.81 valueType=unsigned self.can_1_sig_2_name_u.setText("WheelSpeed_FR") # Unit=bar StartBits=48 length=8 ByteOrder=Intel Offset=0 Factor=1 Min=0 Max=254 ValueType=unsigned self.can_1_sig_3_name_u.setText("BrakePressure") #Set CAN message 2 ABS_ESC_1 (0x92) DLC=2 CycleTime=100ms self.can_2_enable_u.setChecked(True) self.can_2_enable_u.setText("BCM_2 (0x104/260D)") # Unit=bits StartBits=10 length=2 ByteOrder=Intel Offset=0 Factor=1 Min=0 Max=3 valueType=unsigned self.can_2_sig_1_name_u.setText("TurnIndictors") # Unit=bits StartBits=8 length=2 ByteOrder=Intel Offset=0 Factor=1 Min=0 Max=3 valueType=unsigned self.can_2_sig_2_name_u.setText("LowBeam") # Unit=bits StartBits=12 length=2 ByteOrder=Intel Offset=0 Factor=1 Min=0 Max=3 valueType=unsigned self.can_2_sig_3_name_u.setText("TransportMode") #self.soap_enable_button_u.setChecked(True) self.soap_server_address_u.setText("http://192.168.5.16:8080/PacketDispatcher/Packet?wsdl") self.soap_server_address_u.setEnabled(False) self.soap_server_address_u.setCursorPosition(0) self.kafka_enable_button_u.setChecked(True) self.kafka_server_address_u.setText("localhost:9092") #self.kafka_server_address_u.setEnabled(False) self.kafka_server_address_u.setCursorPosition(0) self.start_button_u.setEnabled(True) self.stop_button_u.setEnabled(False) self.pause_button_u.setEnabled(False) self.start_button_log_u.setEnabled(True) self.stop_button_log_u.setEnabled(False) self.pause_button_log_u.setEnabled(False) self.start_button_u.setIcon(QtGui.QIcon("icons/start_16.png")) self.stop_button_u.setIcon(QtGui.QIcon("icons/stop_16.png")) self.pause_button_u.setIcon(QtGui.QIcon("icons/pause_16.png")) self.start_button_log_u.setIcon(QtGui.QIcon("icons/start_16.png")) self.stop_button_log_u.setIcon(QtGui.QIcon("icons/stop_16.png")) self.pause_button_log_u.setIcon(QtGui.QIcon("icons/pause_16.png")) self.paused = False self.started = False self.stopped = True self.timers = [] self.gpsIndex = 0 self.gps_direction = 1 self.lcd_timer = QtCore.QTimer() self.lcd_timer.timeout.connect(self.update_lcd) self.lcd_timer.start(1000) self.gps_enable_u.setChecked(True) self.single_shot_enable_u.setChecked(True)
def open_selected_event_from_table(self): """ Button - Open EVENT | gallery from table event """ # Get selected rows self.tbl_event = self.dialog.findChild(QTableView, "tbl_event_node") selected_list = self.tbl_event.selectionModel().selectedRows() if len(selected_list) == 0: message = "Any record selected" self.controller.show_warning(message, context_name='ui_message') return row = selected_list[0].row() self.visit_id = self.tbl_event.model().record(row).value("visit_id") self.event_id = self.tbl_event.model().record(row).value("event_id") # Get all events | pictures for visit_id sql = "SELECT value FROM " + self.schema_name + ".v_ui_om_visit_x_node" sql += " WHERE visit_id = '" + str(self.visit_id) + "'" rows = self.controller.get_rows(sql) # Get absolute path sql = "SELECT value FROM " + self.schema_name + ".config_param_system" sql += " WHERE parameter = 'doc_absolute_path'" row = self.controller.get_row(sql) self.img_path_list = [] self.img_path_list1D = [] # Creates a list containing 5 lists, each of 8 items, all set to 0 # Fill 1D array with full path if row is None: message = "Parameter not set in table 'config_param_system'" self.controller.show_warning(message, parameter='doc_absolute_path') return else: for value in rows: full_path = str(row[0]) + str(value[0]) self.img_path_list1D.append(full_path) # Create the dialog and signals self.dlg_gallery = Gallery() utils_giswater.setDialog(self.dlg_gallery) txt_visit_id = self.dlg_gallery.findChild(QLineEdit, 'visit_id') txt_visit_id.setText(str(self.visit_id)) txt_event_id = self.dlg_gallery.findChild(QLineEdit, 'event_id') txt_event_id.setText(str(self.event_id)) # Add picture to gallery # Fill one-dimensional array till the end with "0" self.num_events = len(self.img_path_list1D) limit = self.num_events % 9 for k in range(0, limit): # @UnusedVariable self.img_path_list1D.append(0) # Inicialization of two-dimensional array rows = self.num_events / 9 + 1 columns = 9 self.img_path_list = [[0 for x in range(columns)] for x in range(rows)] # @UnusedVariable message = str(self.img_path_list) # Convert one-dimensional array to two-dimensional array idx = 0 if rows == 1: for br in range(0, len(self.img_path_list1D)): self.img_path_list[0][br] = self.img_path_list1D[br] else: for h in range(0, rows): for r in range(0, columns): self.img_path_list[h][r] = self.img_path_list1D[idx] idx = idx + 1 # List of pointers(in memory) of clicableLabels self.list_widget = [] self.list_labels = [] for i in range(0, 9): widget_name = "img_" + str(i) widget = self.dlg_gallery.findChild(QLabel, widget_name) if widget: # Set image to QLabel pixmap = QPixmap(str(self.img_path_list[0][i])) pixmap = pixmap.scaled(171, 151, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) widget.setPixmap(pixmap) self.start_indx = 0 self.clickable(widget).connect(partial(self.zoom_img, i)) self.list_widget.append(widget) self.list_labels.append(widget) self.start_indx = 0 self.btn_next = self.dlg_gallery.findChild(QPushButton, "btn_next") self.btn_next.clicked.connect(self.next_gallery) self.btn_previous = self.dlg_gallery.findChild(QPushButton, "btn_previous") self.btn_previous.clicked.connect(self.previous_gallery) self.set_icon(self.btn_previous, "109") self.set_icon(self.btn_next, "108") self.btn_close = self.dlg_gallery.findChild(QPushButton, "btn_close") self.btn_close.clicked.connect(self.dlg_gallery.close) self.dlg_gallery.exec_()
class VCSIndicator: " Holds an indicator properties " def __init__(self, configLine): """ Config line looks as follows: id:::pathOrString:::ForegroundColor:::BackgroundColor:::Tooltip It comes from a config file or from a plugin """ self.identifier = None self.pixmap = None self.text = None self.backgroundColor = None self.foregroundColor = None self.defaultTooltip = "" self.__parseConfigLine(configLine) return def __parseConfigLine(self, configLine): " Fills the members " if type(configLine) == tuple or type(configLine) == list: # Came from a plugin self.__parsePluginProvidedTuple(configLine) else: # Came from a config file self.__parseConfigFileProvidedString(configLine) self.__scalePixmap() return def __setBrokenIndicator(self, msg): " Sets the indicator to the broken state " self.text = BROKEN_INDICATOR self.backgroundColor = QColor(0, 255, 255) self.foregroundColor = QColor(255, 0, 0) self.defaultTooltip = msg return def __parseConfigFileProvidedString(self, configLine): " Parses config file provided values " parts = configLine.split(":::") if len(parts) != 5: raise Exception("Unexpected format of an indicator " "description. Expected 5 values.") # ID field self.identifier = int(parts[0]) # path or text field if os.path.isabs(parts[1]): # That must be a path to the pixmap try: self.pixmap = QPixmap(parts[1]) except: self.__setBrokenIndicator("Failed to load pixmap from " + parts[1]) return else: # Try to find the pixmap in the standard pixmap directory candidate = parts[1].strip() searchPath = os.path.dirname( os.path.abspath( sys.argv[0] ) ) + \ os.path.sep + 'pixmaps' + os.path.sep + candidate if candidate != "" and os.path.exists(searchPath): try: self.pixmap = QPixmap(searchPath) except: self.__setBrokenIndicator("Failed to load pixmap from " + parts[1]) return else: # It is just a text. Cut it to up to 2 letters self.__setText(parts[1]) # Foreground color if parts[2].lower() == "none": self.foregroundColor = None else: self.foregroundColor = buildColor(parts[2]) # Background color if parts[3].lower() == "none": self.backgroundColor = None else: self.backgroundColor = buildColor(parts[3]) # Default tooltip if parts[4].lower() == "none": self.defaultTooltip = "" else: self.defaultTooltip = str(parts[4]).strip() return def __parsePluginProvidedTuple(self, pluginIndicator): " Checks what plugin provided " if len(pluginIndicator) != 5: raise Exception("Unexpected format of an indicator " "description. Expected 5 values.") # ID field self.identifier = int(pluginIndicator[0]) # Pixmap/text field if type(pluginIndicator[1]) == str: self.__setText(pluginIndicator[1]) else: try: self.pixmap = QPixmap(pluginIndicator[1]) except: self.__setBrokenIndicator("Failed to get plugin indicator " "pixmap. Indicator id: " + str(self.identifier)) return # Foreground color if pluginIndicator[2] is None: self.foregroundColor = None else: if type(pluginIndicator[2]) == str: self.foregroundColor = buildColor(pluginIndicator[2]) else: self.foregroundColor = QColor(pluginIndicator[2]) # Background color if pluginIndicator[3] is None: self.backgroundColor = None else: if type(pluginIndicator[3]) == str: self.backgroundColor = buildColor(pluginIndicator[3]) else: self.backgroundColor = QColor(pluginIndicator[3]) # Default tooltip if pluginIndicator[4] is None: self.defaultTooltip = "" else: self.defaultTooltip = str(pluginIndicator[4]).strip() return def __setText(self, value): " Sets the indicator text " if len(value) > MAX_TEXT_INDICATOR_LENGTH: self.text = value[:MAX_TEXT_INDICATOR_LENGTH] else: self.text = value self.text = self.text.strip() return def __scalePixmap(self): " Scales the pixmap if necessary " if self.pixmap is None: return if self.pixmap.width() > MAX_PIXMAP_INDICATOR_WIDTH or \ self.pixmap.height() > MAX_PIXMAP_INDICATOR_HEIGHT: maxSize = QSize(MAX_PIXMAP_INDICATOR_WIDTH, MAX_PIXMAP_INDICATOR_HEIGHT) self.pixmap = self.pixmap.scaled(maxSize, Qt.KeepAspectRatio) return def isPixmap(self): " True if it is a pixmap label " return self.pixmap is not None def draw(self, label): " Draws the indicator as members tell. label is QLabel " label.setPalette(QLabel().palette()) if self.isPixmap(): label.setAutoFillBackground(False) label.setFrameStyle(QLabel().frameStyle()) label.setPixmap(self.pixmap) else: label.setFrameStyle(QFrame.StyledPanel) label.setAutoFillBackground(True) palette = label.palette() if self.backgroundColor is not None: palette.setColor(QPalette.Background, self.backgroundColor) if self.foregroundColor is not None: palette.setColor(QPalette.Foreground, self.foregroundColor) label.setPalette(palette) label.setText(self.text) return
class CImprovedPanel(QFrame): def __init__(self, parent=None): QFrame.__init__(self, parent) #FADING self.__opacity_effect = QGraphicsOpacityEffect() self.__fading_timer = QTimer(parent) self.__fading_timer.timeout.connect(self.__on_fading_timer) self.__FADE_TYPE = Enum("IN", "OUT") self.__fade_time = 20 self.__opacity = 1.0 self.__opacity_fading_coefficient = 0.02 self.__selected_fade_type = self.__FADE_TYPE.IN self.resizeEvent = self.__onResize #MOVE self.__move_animation_type = QEasingCurve.Linear self.__move_time = 350 self.__is_moving = False #RESIZE self.__resize_animation_type = QEasingCurve.Linear self.__resize_time = 700 self.__is_resizing = False #PIXMAP & MASCHERA self.__pmap = QPixmap(self.size()) self.__pmap_fname = "" self.__show_mask_preview = False #SHADOW self.__shadow_Xoffset = 3.0 #default value self.__shadow_Yoffset = 3.0 #default value self.__shadow_blur_radius = 8.0 #default value self.__shadow_color = QColor(38,38,38,150) #default value self.__shadow_effect = QGraphicsDropShadowEffect() self.__shadow_effect.setXOffset(self.__shadow_Xoffset) self.__shadow_effect.setYOffset(self.__shadow_Yoffset) self.__shadow_effect.setBlurRadius(self.__shadow_blur_radius) self.__shadow_effect.setColor(self.__shadow_color) self._shadow_visible = False ##FUNZIONI PER FADING def fadeIn(self): """ Labels fades in from completely invisible to completely visible. """ self.__opacity = 0.0 self.__selected_fade_type = self.__FADE_TYPE.IN self.__fading_timer.start(self.__fade_time) def fadeOut(self): """ Labels fades out from completely visible to completely invisible. """ self.__selected_fade_type = self.__FADE_TYPE.OUT self.__fading_timer.start(self.__fade_time) def setFadeTime(self, value): """ Sets fading time. Everytime interval is reached, alpha is increased (or decreased) by __opacity_fading_coefficient. @param value: fade time (msec) @type value: int """ self.__fade_time = value def getFadeTime(self): return self.__fade_time fadeInterval = QtCore.pyqtProperty("int", getFadeTime, setFadeTime) def setFadeCoefficient(self, value): """ Sets fading coefficient. Alpha is increased (or decreased) by this value. @param value: coefficient (min 0.0 - max 1.0) @type value: float """ self.__opacity_fading_coefficient = value def getFadeCoefficient(self): return self.__opacity_fading_coefficient fadeCoefficient = QtCore.pyqtProperty("double", getFadeCoefficient, setFadeCoefficient) def __on_fading_timer(self): if self.__selected_fade_type == self.__FADE_TYPE.OUT: if self.__opacity > 0: self.__opacity -= self.__opacity_fading_coefficient self.__opacity_effect.setOpacity(self.__opacity) self.setGraphicsEffect(self.__opacity_effect) else: self.__fading_timer.stop() if self.__selected_fade_type == self.__FADE_TYPE.IN: if self.__opacity <= 1.0: self.__opacity += self.__opacity_fading_coefficient self.__opacity_effect.setOpacity(self.__opacity) self.setGraphicsEffect(self.__opacity_effect) else: self.__fading_timer.stop() ## FUNZIONI PER SPOSTAMENTO VERSO PUNTO (ANIMATO) def setMoveAnimationType(self, animation_type): """ Sets move animation type. @param animation_type: animation type @type animation_type: QtEasingCurve """ self.__move_animation_type = animation_type def getMoveAnimationType(self): return self.__move_animation_type #asd = QtCore.pyqtProperty("QEasingCurve", getMoveAnimationType, setMoveAnimationType) #sembra nn essere supportato per ora (06/05/2013) def setMoveTime(self, value): """ Sets animation moving time. @param value: animation time (duration) (msec) @type value: int """ self.__move_time = value def getMoveTime(self): return self.__move_time moveTime = QtCore.pyqtProperty("int", getMoveTime, setMoveTime) def setResizeTime(self, value): """ Sets animation resize time. @param value: animation time (duration) (msec) @type value: int """ self.__resize_time = value def getResizeTime(self): return self.__resize_time resizeTime = QtCore.pyqtProperty("int", getResizeTime, setResizeTime) def moveTo(self, x, y): """ Move itself to a given point with the given animation in the given duration. @param x: X point coordinate @type x: int @param y: Y point coordinate @type y: int """ if self.__is_moving: return self.__is_moving = True self.__starting_position = QPoint(self.pos()) self.__moveAnimation = QPropertyAnimation(self, "pos", self) self.__moveAnimation.finished.connect(self.__on_finished_moving) self.__moveAnimation.setDuration(self.__move_time) self.__moveAnimation.setEasingCurve(self.__move_animation_type) self.__moveAnimation.setStartValue(self.__starting_position) self.__moveAnimation.setEndValue(QPoint(x, y)) self.__moveAnimation.start() def hideLeft(self): """ Panel hides sliding on the left. The slide amount is equal to his width - 5px. """ dest_x = self.geometry().x() - self.width() - 5 dest_y = self.geometry().y() self.moveTo(dest_x, dest_y) def showFromLeft(self): """ Panel shows sliding from the left. The slide amount is equal to his width + 5px. """ dest_x = self.geometry().x() + self.width() + 5 dest_y = self.geometry().y() self.moveTo(dest_x, dest_y) def hideRight(self): """ Panel hides sliding on the right. The slide amount is equal to his width - 5px. """ dest_x = self.geometry().x() + self.width() + 5 dest_y = self.geometry().y() self.moveTo(dest_x, dest_y) def showFromRight(self): """ Panel shows sliding from the right. The slide amount is equal to his width + 5px. """ dest_x = self.geometry().x() - self.width() - 5 dest_y = self.geometry().y() self.moveTo(dest_x, dest_y) def hideTop(self): """ Panel hides sliding on the top. The slide amount is equal to his height - 5px. """ dest_x = self.geometry().x() dest_y = self.geometry().y() - self.height() - 5 self.moveTo(dest_x, dest_y) def showFromTop(self): """ Panel shows sliding from the top. The slide amount is equal to his height - 5px. """ dest_x = self.geometry().x() dest_y = self.geometry().y() + self.height() - 5 self.moveTo(dest_x, dest_y) def hideBottom(self): """ Panel hides sliding to the bottom. The slide amount is equal to his height - 5px. """ dest_x = self.geometry().x() dest_y = self.geometry().y() + self.height() + 5 self.moveTo(dest_x, dest_y) def showFromBottom(self): """ Panel hides sliding from the bottom. The slide amount is equal to his height - 5px. """ dest_x = self.geometry().x() dest_y = self.geometry().y() - self.height() - 5 self.moveTo(dest_x, dest_y) def returnToOriginalPoint(self): """ Panel returns in its original position. The original position is stored when calling moveTo() method. """ if self.__is_moving: return self.__is_moving = True self.__moveAnimation = QPropertyAnimation(self, "pos", self) self.__moveAnimation.finished.connect(self.__on_finished_moving) self.__moveAnimation.setDuration(self.__move_time) self.__moveAnimation.setEasingCurve(self.__move_animation_type) self.__moveAnimation.setStartValue(QPoint(self.pos().x(), self.pos().y())) self.__moveAnimation.setEndValue(self.__starting_position) self.__moveAnimation.start() #FUNZIONI PER RIDIMENSIONAMENTO def setResizeAnimationType(self, animation_type): """ Sets move animation type. @param animation_type: animation type @type animation_type: QtEasingCurve """ self.__resize_animation_type = animation_type def resizeTo(self, width, height): """ Resize itself to a given size with the given animation in the given duration. @param width: New width @type width: int @param height: New height @type height: int """ if self.__is_resizing: return self.__is_resizing = True self.__original_size = self.geometry() self.__resizeAnimation = QPropertyAnimation(self, "geometry", self) self.__resizeAnimation.finished.connect(self.__on_finished_resizing) self.__resizeAnimation.setDuration(self.__resize_time) self.__resizeAnimation.setEasingCurve(self.__resize_animation_type) self.__resizeAnimation.setStartValue(self.__original_size) self.__resizeAnimation.setEndValue(QRect(self.pos().x(), self.pos().y(), width, height)) self.__resizeAnimation.start() def foldLeft(self): """ Panel hides folding to the left. """ new_width = 0 new_height = self.height() self.resizeTo(new_width, new_height) def unfoldLeft(self): """ Panel shows folding from the left. """ new_width = self.__original_size.width() new_height = self.height() self.resizeTo(new_width, new_height) def foldTop(self): """ Panel hides folding to the top. """ new_width = self.width() new_height = 0 self.resizeTo(new_width, new_height) def unfoldTop(self): """ Panel shows folding from the top. """ new_width = self.width() new_height = self.__original_size.height() self.resizeTo(new_width, new_height) #FUNZIONI PER PIXMAP & MASCHERA def setPixmapFile(self, image_file): self.__pmap = image_file self.__pmap.scaled(self.size()) #NB: Il pixmap deve essere BIANCO e NERO. Con heuristicMask il primo pixel in alto a sinistra (0,0) viene #usato per decidere il colore trasparente, tutto il resto è visibile. def getPixmapFile(self): return self.__pmap pixmapFile = QtCore.pyqtProperty("QPixmap", getPixmapFile, setPixmapFile) def applyMask(self, bool): self.__show_mask_preview = bool if bool: self.setMask(QBitmap(self.__pmap.createHeuristicMask().scaled(self.size()))) else: self.setMask(QBitmap()) def getMask(self): return self.__show_mask_preview appliedMask = QtCore.pyqtProperty("bool", fget=getMask, fset=applyMask) def __on_finished_moving(self): self.__is_moving = False def __on_finished_resizing(self): self.__is_resizing = False def __onResize(self, event): self.__pmap.scaled(self.size()) if self.__show_mask_preview: self.setMask(QBitmap(self.__pmap.createHeuristicMask().scaled(self.size()))) #FUNZIONI PER SHADOW def getShadow(self): return self._shadow_visible def setShadow(self, bool): self.setGraphicsEffect(self.__shadow_effect) self._shadow_visible = bool self.__shadow_effect.setEnabled(bool) shadow = QtCore.pyqtProperty("bool", fget=getShadow, fset=setShadow) def setShadowXOffset(self, value): """ Sets shadow offset on X. @param value: offset @type value: float """ self.__shadow_Xoffset = value self.__shadow_effect.setXOffset(self.__shadow_Xoffset) def getShadowXOffset(self): return self.__shadow_Xoffset shadowXOffset = QtCore.pyqtProperty("double", getShadowXOffset, setShadowXOffset) def setShadowYOffset(self, value): """ Sets shadow offset on Y. @param value: offset @type value: float """ self.__shadow_Yoffset = value self.__shadow_effect.setYOffset(self.__shadow_Yoffset) def getShadowYOffset(self): return self.__shadow_Yoffset shadowYOffset = QtCore.pyqtProperty("double", getShadowYOffset, setShadowYOffset) def setShadowBlur(self, value): """ Sets blurred effect on item's shadow. @param value: coefficient @type value: float """ self.__shadow_blur_radius = value self.__shadow_effect.setBlurRadius(self.__shadow_blur_radius) def getShadowBlur(self): return self.__shadow_blur_radius shadowBlur = QtCore.pyqtProperty("double", getShadowBlur, setShadowBlur) def setShadowColor(self, color): """ Sets shadow's color. @param color: value @type color: color """ self.__shadow_color = color self.__shadow_effect.setColor(self.__shadow_color) def getShadowColor(self): return self.__shadow_color
def setsplash(self, splash): pixmap = QPixmap(splash) w = self.splashlabel.width() h = self.splashlabel.height() self.splashlabel.setPixmap(pixmap.scaled(w,h, Qt.KeepAspectRatio))