def __init__(self, name, x, y, points, abs = None, color = None): QWidget.__init__(self) self.setupUi(self) self.name = name self.lineEdit_curve_name.setText(name) logger.debug("from curve: {} {}".format(x, y)) self.coordinates = "[x=" + str(x) + ", y=" + str(y) + "]" self.label_coordinates.setText(self.coordinates) if color is None: logger.debug("len(colors): {}".format(len(COLORS))) color = COLORS[ random.randint(0, len(COLORS) - 1) ] logger.debug("color from creation courbe: {}".format(color)) self.color = color if abs: self.abs = abs else: self.abs = None pixmap = QPixmap(self.pushButton_color.size()) pixmap.fill(QColor(LETTERSTONAMECOLOR[self.color])) icon = QIcon(pixmap) self.pushButton_color.setIcon(icon) self.points = points # self.connect(self.lineEdit_curve_name, SIGNAL("textChanged(str)"), self, SIGNAL("curveTitleChanged(str)")) self.connect(self.lineEdit_curve_name, SIGNAL("editingFinished()"), self.set_name) self.connect(self.pushButton_color, SIGNAL("clicked()"), self.set_color) self.connect(self.pushButton_delete_curve, SIGNAL("clicked()"), self, SIGNAL("deleteCurve()")) self.connect(self.checkBox_curve_visible, SIGNAL("stateChanged(int)"), self.change_state)
def main(): app = QApplication(sys.argv) widget = QWidget() QPixmap.grabWidget(widget, 100, 100, 200, 200) widget.show() app.exec_() e = Event() e.capture = False e.daemon = False e.start() while True: if e.is_press and e.is_release: if e.press_cnt == 1: if e.start_x > e.end_x: e.start_x, e.end_x = e.end_x, e.start_x if e.start_y > e.end_y: e.start_y, e.end_y = e.end_y, e.start_y width = e.end_x - e.start_x height = e.end_y - e.start_y f = tempfile.NamedTemporaryFile( prefix='screentshot_', suffix='.png') command = "import -window root -crop '%sx%s+%s+%s' " %( width, height, e.start_x, e.start_y) command += f.name EasyProcess(command).call() im = Image.open(f.name) im.show() break e.stop()
def decorate_welcome_icon(icon, background_color): """Return a `QIcon` with a circle shaped background. """ welcome_icon = QIcon() sizes = [32, 48, 64, 80] background_color = NAMED_COLORS.get(background_color, background_color) background_color = QColor(background_color) grad = radial_gradient(background_color) for size in sizes: icon_pixmap = icon.pixmap(5 * size / 8, 5 * size / 8) icon_size = icon_pixmap.size() icon_rect = QRect(QPoint(0, 0), icon_size) pixmap = QPixmap(size, size) pixmap.fill(QColor(0, 0, 0, 0)) p = QPainter(pixmap) p.setRenderHint(QPainter.Antialiasing, True) p.setBrush(QBrush(grad)) p.setPen(Qt.NoPen) ellipse_rect = QRect(0, 0, size, size) p.drawEllipse(ellipse_rect) icon_rect.moveCenter(ellipse_rect.center()) p.drawPixmap(icon_rect.topLeft(), icon_pixmap) p.end() welcome_icon.addPixmap(pixmap) return welcome_icon
def data(self, index, role): if role == Qt.EditRole and index.column() == self.ColumnID.Color: return (self._elements[index.row()].brushColor(), self._elements[index.row()].pmapColor()) elif role == Qt.ToolTipRole and index.column() == self.ColumnID.Color: return ("Hex code : {}\nDouble click to change".format( self._elements[index.row()].brushColor().name())) elif role == Qt.DecorationRole and index.column() == self.ColumnID.Color: row = index.row() value = self._elements[row] if value.brushColor == value.pmapColor(): pixmap = QPixmap(_NPIXELS, _NPIXELS) pixmap.fill(value.brushColor) else: a = value.brushColor().rgba() b = value.pmapColor().rgba() img = QImage(_NPIXELS,_NPIXELS, QImage.Format_RGB32) for i in range(_NPIXELS): for j in range(0, _NPIXELS - i): img.setPixel(i, j, a) for i in range(_NPIXELS): for j in range(_NPIXELS - i, _NPIXELS): img.setPixel(i, j, b) pixmap = QPixmap.fromImage(img) icon = QIcon(pixmap) return icon else: return ListModel.data(self,index,role)
def __init__(self, widget, parent=None, name=None): OWPlot.__init__(self, parent, name, axes=[], widget=widget) ScaleData.__init__(self) self.update_antialiasing(False) self.widget = widget self.last_selected_curve = None self.enableGridXB(0) self.enableGridYL(0) self.domain_contingencies = None self.auto_update_axes = 1 self.old_legend_keys = [] self.selection_conditions = {} self.attributes = [] self.visualized_mid_labels = [] self.attribute_indices = [] self.valid_data = [] self.groups = {} self.colors = None self.selected_examples = [] self.unselected_examples = [] self.bottom_pixmap = QPixmap(gui.resource_filename("icons/upgreenarrow.png")) self.top_pixmap = QPixmap(gui.resource_filename("icons/downgreenarrow.png"))
def __updatePixmap(self): """ Update the cached shadow pixmap. """ rect_size = QSize(50, 50) left = top = right = bottom = self.radius_ # Size of the pixmap. pixmap_size = QSize(rect_size.width() + left + right, rect_size.height() + top + bottom) shadow_rect = QRect(QPoint(left, top), rect_size) pixmap = QPixmap(pixmap_size) pixmap.fill(QColor(0, 0, 0, 0)) rect_fill_color = self.palette().color(QPalette.Window) pixmap = render_drop_shadow_frame( pixmap, QRectF(shadow_rect), shadow_color=self.color_, offset=QPointF(0, 0), radius=self.radius_, rect_fill_color=rect_fill_color ) self.__shadowPixmap = pixmap self.update()
def set_face_img(self, avatar): from PyQt4.QtGui import QPixmap pixmap = QPixmap() pixmap.loadFromData(avatar) self.avatar_base64 = avatar self.mw.avatar.setPixmap(pixmap)
def set_color(self, color): if color != self._color: self._color = color self.emit(SIGNAL("colorChanged(QColor)"), self._color) pixmap = QPixmap(self.iconSize()) pixmap.fill(color) self.setIcon(QIcon(pixmap))
def get_screen_by_qt(self, x1=None, y1=None, x2=None, y2=None): from PyQt4.QtGui import QPixmap, QApplication from PyQt4.Qt import QBuffer, QIODevice import StringIO app = QApplication(sys.argv) _buffer = QBuffer() _buffer.open(QIODevice.ReadWrite) desktop = QApplication.desktop() #width = desktop.screenGeometry().width() #height = desktop.screenGeometry().height() if x1 is None: x1 = 0 if y1 is None: y1 = 0 if x2 is None: x2 = -1 else: x2 -= x1 if y2 is None: y2 = -1 else: y2 -= y1 QPixmap.grabWindow(desktop.winId(), x1, y1, x2, y2) \ .save(_buffer, 'png') strio = StringIO.StringIO() strio.write(_buffer.data()) _buffer.close() del app strio.seek(0) return Image.open(strio)
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)
class EkdColorPropertie(EkdPropertie): """ Définition de la propriété correspondant à une Couleur """ def __init__(self, prop, name, value, section=None ): super(EkdColorPropertie, self).__init__(prop, name, value, EkdPropertie.COLOR, section) self.label = QLabel(name) self.widget = QFrame() self.layout = QHBoxLayout(self.widget) self.line = QLineEdit(value) self.value = value self.line.setReadOnly(True) self.layout.addWidget(self.line) self.color = QPixmap(15, 15) self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16)))) self.boutton = QPushButton(QIcon(self.color), u"") self.boutton.setFixedSize(25,25) self.layout.addWidget(self.boutton) # Quand on clique sur le boutton on défini la couleur self.connect(self.boutton, SIGNAL("clicked()"), self.updateColor) def updateColor(self): newcolor = QColorDialog.getColor(QColor.fromRgb(int("%d" % int(self.value, 16))), None )# Non supporté sous Jaunty ?? if newcolor.isValid(): self.value = str("%x" % newcolor.rgb())[2:] self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16)))) self.boutton.setIcon(QIcon(self.color)) self.line.setText(self.value) EkdConfig.set(self.section, self.id, self.value)
def show(cursor, pos=None, num_lines=6): """Displays a tooltip showing part of the cursor's Document. If the cursor has a selection, those blocks are displayed. Otherwise, num_lines lines are displayed. If pos is not given, the global mouse position is used. """ block = cursor.document().findBlock(cursor.selectionStart()) c2 = QTextCursor(block) if cursor.hasSelection(): c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor) c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) else: c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor, num_lines) data = textformats.formatData('editor') doc = QTextDocument() font = QFont(data.font) font.setPointSizeF(font.pointSizeF() * .8) doc.setDefaultFont(font) doc.setPlainText(c2.selection().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlighter.highlight(doc, state=tokeniter.state(block)) size = doc.size().toSize() + QSize(8, -4) pix = QPixmap(size) pix.fill(data.baseColors['background']) doc.drawContents(QPainter(pix)) label = QLabel() label.setPixmap(pix) label.setStyleSheet("QLabel { border: 1px solid #777; }") label.resize(size) widgets.customtooltip.show(label, pos)
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 loadImage(self, data, scaled=True, fromfile=True): """ Load the image into the widget using a bytearray An empty picture will result in the default placeholder image. """ if data is None or not data: self.removeImage() return if fromfile: pix = QPixmap(data) elif isinstance(data, QPixmap): pix = data else: pix = QPixmap() r = pix.loadFromData(data, "JPG") if not r: pix = QPixmap(data) self._orignalimage = QPixmap(pix) h = self.maximumHeight() if scaled: pix = pix.scaledToHeight(h, Qt.SmoothTransformation) self.image.setPixmap(pix) self.isDefault = False
def impl(self): try: # Capture the window before we change anything beforeImg = QPixmap.grabWindow( self.w.winId() ).toImage() # Change the visibility of the *selected* layer self.o2.visible = False self.w.repaint() # Make sure the GUI is caught up on paint events QApplication.processEvents() # We must sleep for the screenshot to be right. time.sleep(0.1) # Capture the window now that we've changed a layer. afterImg = QPixmap.grabWindow( self.w.winId() ).toImage() # Optional: Save the files so we can inspect them ourselves... #beforeImg.save('before.png') #afterImg.save('after.png') # Before and after should NOT match. assert beforeImg != afterImg except: # Catch all exceptions and print them # We must finish so we can quit the app. import traceback traceback.print_exc() TestLayerWidget.errors = True qApp.quit()
def setCurrentIndex(self, index): """ Set the current shown widget index. """ index = max(min(index, self.count() - 1), 0) if self.__currentIndex == -1: self.layout().setCurrentIndex(index) self.__currentIndex = index return # if not self.animationEnabled(): # self.layout().setCurrentIndex(index) # self.__currentIndex = index # return # else start the animation current = self.__widgets[self.__currentIndex] next_widget = self.__widgets[index] current_pix = QPixmap.grabWidget(current) next_pix = QPixmap.grabWidget(next_widget) with updates_disabled(self): self.__fadeWidget.setPixmap(current_pix) self.__fadeWidget.setPixmap2(next_pix) self.__nextCurrentIndex = index self.__transitionStart()
def __initializeUi(self): """ Initializes the Widget ui. """ self.__clearButton.setCursor(Qt.ArrowCursor) if self.__uiClearImage and self.__uiClearClickedImage: pixmap = QPixmap(self.__uiClearImage) clickedPixmap = QPixmap(self.__uiClearClickedImage) self.__clearButton.setIcon(QIcon(pixmap)) self.__clearButton.setMaximumSize(pixmap.size()) # Signals / Slots. self.__clearButton.pressed.connect(functools.partial(self.__clearButton.setIcon, QIcon(clickedPixmap))) self.__clearButton.released.connect(functools.partial(self.__clearButton.setIcon, QIcon(pixmap))) else: self.__clearButton.setText("Clear") self.__setStyleSheet() frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) self.setMinimumSize( max(self.minimumSizeHint().width(), self.__clearButton.sizeHint().height() + frameWidth * 2), max(self.minimumSizeHint().height(), self.__clearButton.sizeHint().height() + frameWidth * 2), ) self.__completer.setCaseSensitivity(Qt.CaseInsensitive) self.__completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
def set_verify_code(self, data): this = self.mw from PyQt4.QtGui import QPixmap pixmap = QPixmap() pixmap.loadFromData(data) this.login_vcimg.setPixmap(pixmap) this.login_vcimg.show()
def addPreviewImage(self, color_image, parent = None): image = color_image image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if not parent is None: parent.progress_bar.setValue(12) h, w = image.shape self.img_height = h self.ocr_areas = OCRAreasFinder(color_image, self.settings["contrast"]) self.market_width = self.ocr_areas.market_width if not parent is None: parent.progress_bar.setValue(14) self.valid_market = self.ocr_areas.valid if self.valid_market: points = self.ocr_areas.market_table self.market_offset = (points[0][0], points[0][1]) station = self.ocr_areas.station_name self.station_offset = (station[0][0], station[0][1]) cut = image[0:points[1][1] + 20, 0:points[1][0] + 20] else: cut = image[:] self.market_offset = (0, 0) self.station_offset = (0, 0) processedimage = array2qimage(cut) if not parent is None: parent.progress_bar.setValue(16) pix = QPixmap() pix.convertFromImage(processedimage) if not parent is None: parent.progress_bar.setValue(18) return pix
def set_color(self): # couleur = QtGui.QColorDialog.getColor(QtCore.Qt.white) testqt, ok = QInputDialog.getItem(None, "Couleur", "Selection d'une couleur", self.lettersToQColor.keys(), False) if ok: # couleur = self.nameColorsToLetters[testqt] couleur = self.lettersToQColor[testqt] logger.debug(couleur) self.color = self.frenchToLetter[testqt] else: couleur = self.lettersToQColor['noir'] self.color = 'b' # self.color = str(couleur.name()) # logger.debug( couleur.name()) # self.color = self.lettersToNameColor[testqt] pixmap = QPixmap(self.pushButton_color.size()) # pixmap.fill(QColor(self.color)) pixmap.fill(couleur) icon = QIcon(pixmap) self.pushButton_color.setIcon(icon) # logger.debug( QColor(self.color) ) # self.pushButton_color.setStyleSheet("background-color: " + self.color ) # palette = QtGui.QPalette() # palette.setColor(QtGui.QPalette.ButtonText, self.lettersToQColor[testqt]) # palette.setColor(10, couleur) # self.pushButton_color.setPalette(palette) self.emit(SIGNAL("colorChanged"))
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 saveWindow(self, fileName=None, fileType=None, window=False): self.repaint() # make sure we are uptodate if window: pixmap = QPixmap.grabWindow(self.winId()) else: pixmap = QPixmap.grabWidget(self) if not fileName: fileTypes = {unicode(QCoreApplication.translate('SubWindow', 'PNG - compressed image')):('png',), unicode(QCoreApplication.translate('SubWindow', 'JPEG - picture')):('jpg', 'jpeg'), unicode(QCoreApplication.translate('SubWindow', 'BMP - uncompressed bitmap')):('bmp',)} filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()]) dlg = QFileDialog(self, QCoreApplication.translate('SubWindow', 'Select name of file to save'), Globals.defaultFolder or '', filters) dlg.setFileMode(QFileDialog.AnyFile) dlg.setAcceptMode(QFileDialog.AcceptSave) if dlg.exec_() != QDialog.Accepted: return tmp = unicode(dlg.selectedFilter()) fileType = tmp[:tmp.find('(')-1] dlg.setDefaultSuffix(fileTypes[fileType][0]) files = dlg.selectedFiles() if not files: return fileName = unicode(files[0]) Globals.defaultFolder, tmp = os.path.split(fileName) try: pixmap.save(unicode(fileName)) except: QMessageBox.critical(self, QCoreApplication.translate('SubWindow', 'Could not save file!'), QCoreApplication.translate('SubWindow', 'Writing failed! Make sure you have write permissions!'))
def updatecanvas(self, canvas): """ Update the canvas object for the legend background. """ if self._lastextent == canvas.extent(): return self._lastextent = canvas.extent() if QGis.QGIS_VERSION_INT > 20200: from qgis.core import QgsMapRendererParallelJob, QgsMapSettings settings = canvas.mapSettings() extent = settings.extent() settings.setOutputSize(self.size()) settings.setExtent(extent) #settings.setFlags(QgsMapSettings.Antialiasing | QgsMapSettings.DrawLabeling ) self.renderjob = QgsMapRendererParallelJob(settings) self.renderjob.finished.connect(self._renderimage) self.renderjob.start() else: if canvas.isDrawing(): return pixmap = QPixmap(self.size()) pixmap.fill(canvas.canvasColor()) painter = QPainter(pixmap) painter.setRenderHints(QPainter.Antialiasing) renderer = canvas.mapRenderer() renderer.render(painter) del painter self.canvasimage = pixmap.toImage() self.update()
def load(self): self.initTranslations() import vtk, VtkWidget, VtkWindow, Objects, Helpers self.vtk = vtk self.VtkWidget = VtkWidget self.VtkWindow = VtkWindow self.Objects = Objects self.Helpers = Helpers xpm = QPixmap() xpm.loadFromData(self.getFile('3dwin.xpm').read()) winIcon = QIcon(xpm) self.winManager = SubWinManager(glb.mainWin.workSpace, self.VtkWindow.VtkWindow, QCoreApplication.translate('VtkWindow', "Vtk Window"), winIcon) testAction = QAction(winIcon, QCoreApplication.translate('VtkWindow', '&VtkWindow Test'), glb.mainWin) testAction.setStatusTip(QCoreApplication.translate('VtkWindow', 'Show a new Vtk test window')) QWidget.connect(testAction, SIGNAL("triggered()"), self.test) glb.mainWin.plugInMenu.addAction(testAction) ftActions = glb.fileTypeActions ftActions.addType('application/x-3ds', '.3ds') ftActions.addAction(self.show3DS, ('application/x-3ds',), QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5) ftActions.addType('application/x-vrml', '.wrl') ftActions.addAction(self.showVRML, ('application/x-vrml',), QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5) return True
def png(nom): u"""Charge l'image <nom>.png depuis le repertoire 'images/'. L'image doit être au format png, et son nom doit indiqué sans l'extension '.png'.""" pixmap = QPixmap() pixmap.load(png_pth(nom), 'PNG') return pixmap
def show(self): self.view = QWidget() mainLayout = QVBoxLayout() self.view.setLayout(mainLayout) transformsLayout = QHBoxLayout() mainLayout.addLayout(transformsLayout) for key, value in self.transforms.iteritems(): transrormLayout = QVBoxLayout() transformsLayout.addLayout(transrormLayout) header = QLabel(key) image = QLabel() image.setPixmap(QPixmap.fromImage(Ipl2QIm(value))) transrormLayout.addWidget(header) transrormLayout.addWidget(image) for symbol in self.symbols: transformsLayout = QHBoxLayout() mainLayout.addLayout(transformsLayout) for key, value in symbol.transforms.iteritems(): transrormLayout = QVBoxLayout() transformsLayout.addLayout(transrormLayout) header = QLabel(key) image = QLabel() image.setPixmap(QPixmap.fromImage(Ipl2QIm(value))) transrormLayout.addWidget(header) transrormLayout.addWidget(image) self.view.show()
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 ResizableImage(QLabel): def __init__(self, filename, height, min_scale, max_scale): super(ResizableImage, self).__init__() self.setAlignment(Qt.AlignCenter) self.full_pixmap = None self.scaled_pixmap = None self.aspect = None self.set_file(filename) self.set_height(height) self.min_height = self.full_pixmap.height() * min_scale * self.aspect self.min_width = self.full_pixmap.width() * min_scale / self.aspect self.max_height = self.full_pixmap.height() * max_scale * self.aspect self.max_width = self.full_pixmap.width() * max_scale / self.aspect def set_file(self, filename): self.full_pixmap = QPixmap(filename) self.aspect = float(self.full_pixmap.height()) / self.full_pixmap.width() if self.scaled_pixmap is not None: self.set_height(self.scaled_pixmap.height()) def set_height(self, height): self.scaled_pixmap = self.full_pixmap.scaledToHeight(height, Qt.SmoothTransformation) self.setPixmap(self.scaled_pixmap) def set_width(self, width): self.scaled_pixmap = self.full_pixmap.scaledToWidth(width, Qt.SmoothTransformation) self.setPixmap(self.scaled_pixmap) def resizeEvent(self, ev): width, height = ev.size().width(), ev.size().height() label_aspect = height / width if label_aspect > self.aspect: self.set_width(min(max(.9 * width, self.min_width), self.max_width)) else: self.set_height(min(max(.9 * height, self.min_height), self.max_height))
def __init__(self, parent, delegate): QWidget.__init__(self, parent) self.delegate = delegate self.emitted = False self.ui = Ui_AskVerdict() self.ui.setupUi(self) # build verdict icons if not AskVerdict.icons_cache: for text in VERDICTS: color = VERDICT_TO_ROW_COLORS.get(text[0]) pixmap = QPixmap(16, 16) pixmap.fill(Qt.transparent) if color: painter = QPainter(pixmap) painter.setPen(Qt.black) painter.setBrush(color) painter.drawEllipse(0, 0, 15, 15) painter.end() AskVerdict.icons_cache[text] = QIcon(pixmap) # set combo verdict for text in ('other...', 'skip', 'retry'): self.ui.comboVerdict.addItem(AskVerdict.icons_cache[text], text) model = self.ui.comboVerdict.model() model.itemFromIndex(model.index(0, 0)).setSelectable(False) self.ui.comboVerdict.activated.connect(self.on_dropdown_item_activated) self.ui.goodVerdict.clicked.connect(self.on_good_bad_button_clicked) self.ui.goodVerdict.setIcon(AskVerdict.icons_cache["good"]) self.ui.badVerdict.clicked.connect(self.on_good_bad_button_clicked) self.ui.badVerdict.setIcon(AskVerdict.icons_cache["bad"])
def pixmapFromSvg(self, pmapSize=None, withBorders=None): """returns a pixmap with default size as given in SVG and optional borders/shadows""" if withBorders is None: withBorders = Preferences.showShadows if withBorders: wantSize = self.tileset.tileSize.toSize() else: wantSize = self.tileset.faceSize.toSize() if not pmapSize: pmapSize = wantSize result = QPixmap(pmapSize) result.fill(Qt.transparent) painter = QPainter(result) if not painter.isActive(): logException('painter is not active. Wanted size: %s' % str(pmapSize)) try: xScale = float(pmapSize.width()) / wantSize.width() yScale = float(pmapSize.height()) / wantSize.height() except ZeroDivisionError: xScale = 1 yScale = 1 if not withBorders: painter.scale(*self.tileset.tileFaceRelation()) painter.translate(-self.facePos()) renderer = self.tileset.renderer() renderer.render(painter, self.elementId()) painter.resetTransform() self._drawDarkness(painter) if self.showFace(): faceSize = self.tileset.faceSize.toSize() faceSize = QSize(faceSize.width() * xScale, faceSize.height() * yScale) painter.translate(self.facePos()) renderer.render(painter, self.tileset.svgName[self.tile.element.lower()], QRectF(QPointF(), QSizeF(faceSize))) return result
def __init__(self, pixmap=None, parent=None): super().__init__(parent) self.setCacheMode(QGraphicsItem.ItemCoordinateCache) self._pixmap = QPixmap(pixmap) if pixmap is not None else QPixmap() self._keepAspect = True self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
def cursor(name): pix = QPixmap(name) pix = pix.scaled(QSize(24, 24)) return QCursor(pix)
def pixmap(self): return QPixmap(self.__pixmap)
def setPixmap(self, pixmap): if self.__pixmap != pixmap: self.__pixmap = QPixmap(pixmap) self.__updateWindowGeometry() self.update() self.updateGeometry()
class Preview(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__pixmap = QPixmap() # Flag indicating if the widget was resized as a result of user # initiated window resize. When false the widget will automatically # resize/re-position based on pixmap size. self.__hasExplicitSize = False self.__inUpdateWindowGeometry = False def setPixmap(self, pixmap): if self.__pixmap != pixmap: self.__pixmap = QPixmap(pixmap) self.__updateWindowGeometry() self.update() self.updateGeometry() def pixmap(self): return QPixmap(self.__pixmap) def resizeEvent(self, event): super().resizeEvent(event) if self.isVisible() and self.isWindow() and \ not self.__inUpdateWindowGeometry: # mark that we have an explicit user provided size self.__hasExplicitSize = True def __updateWindowGeometry(self): if not self.isWindow() or self.__hasExplicitSize: return def framemargins(widget): frame, geom = widget.frameGeometry(), widget.geometry() return QMargins(geom.left() - frame.left(), geom.top() - frame.top(), geom.right() - frame.right(), geom.bottom() - frame.bottom()) def fitRect(rect, targetrect): size = rect.size().boundedTo(targetgeom.size()) newrect = QRect(rect.topLeft(), size) dx, dy = 0, 0 if newrect.left() < targetrect.left(): dx = targetrect.left() - newrect.left() if newrect.top() < targetrect.top(): dy = targetrect.top() - newrect.top() if newrect.right() > targetrect.right(): dx = targetrect.right() - newrect.right() if newrect.bottom() > targetrect.bottom(): dy = targetrect.bottom() - newrect.bottom() return newrect.translated(dx, dy) margins = framemargins(self) minsize = QSize(120, 120) pixsize = self.__pixmap.size() available = QApplication.desktop().availableGeometry(self) available = available.adjusted(margins.left(), margins.top(), -margins.right(), -margins.bottom()) # extra adjustment so the preview does not cover the whole desktop available = available.adjusted(10, 10, -10, -10) targetsize = pixsize.boundedTo(available.size()).expandedTo(minsize) pixsize.scale(targetsize, Qt.KeepAspectRatio) if not self.testAttribute(Qt.WA_WState_Created) or \ self.testAttribute(Qt.WA_WState_Hidden): center = available.center() else: center = self.geometry().center() targetgeom = QRect(QPoint(0, 0), pixsize) targetgeom.moveCenter(center) if not available.contains(targetgeom): targetgeom = fitRect(targetgeom, available) self.__inUpdateWindowGeometry = True self.setGeometry(targetgeom) self.__inUpdateWindowGeometry = False def sizeHint(self): return self.__pixmap.size() def paintEvent(self, event): if self.__pixmap.isNull(): return sourcerect = QRect(QPoint(0, 0), self.__pixmap.size()) pixsize = QSizeF(self.__pixmap.size()) rect = self.contentsRect() pixsize.scale(QSizeF(rect.size()), Qt.KeepAspectRatio) targetrect = QRectF(QPointF(0, 0), pixsize) targetrect.moveCenter(QPointF(rect.center())) painter = QPainter(self) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.drawPixmap(targetrect, self.__pixmap, QRectF(sourcerect)) painter.end()
def __closePreview(self): if self.__previewWidget is not None: self.__previewWidget.close() self.__previewWidget.setPixmap(QPixmap()) self.__previewWidget.deleteLater() self.__previewWidget = None
def setPixmap(self, pixmap): self._pixmap = QPixmap(pixmap) self.updateGeometry() self.update()
def change(self): if self.state == 0: self.mdiArea.cascadeSubWindows() self.mdiArea.setWindowTitle("Cascade") elif self.state == 1: self.mdiArea.tileSubWindows() self.mdiArea.setWindowTitle("Tile") self.state = (self.state + 1) % 2 if __name__ == "__main__": app = QApplication(sys.argv) pixmap = QPixmap(16, 16) pixmap.fill(QColor(0, 0, 0, 0)) icon = QIcon(pixmap) app.setWindowIcon(icon) mdiArea = QMdiArea() textEdit = QTextEdit() textEdit.setPlainText("Qt Quarterly is a paper-based newsletter " "exclusively available to Qt customers. Every " "quarter we mail out an issue that we hope will " "bring added insight and pleasure to your Qt " "programming, with high-quality technical articles " "written by Qt experts.") textWindow = mdiArea.addSubWindow(textEdit) textWindow.setWindowTitle("A Text Editor")
def set_widgets(self): """Set widgets on the Extent Disjoint tab""" self.lblIconDisjoint_3.setPixmap( QPixmap(resources_path('img', 'wizard', 'icon-stop.svg')))
def __init__(self, canvas, button): QgsMapTool.__init__(self, canvas) self.canvas = canvas # self.cursor = QCursor(Qt.CrossCursor) self.cursor = QCursor(QPixmap(identify_cursor), 1, 1) self.button = button
def image(self): pixmap = self._makePixmap(self.widthSpinBox.value(), self.heightSpinBox.value()) return QPixmap.toImage(pixmap)
def __init__(self, parent, distanceUnit, distanceUnit1=None): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("DistanceBoxPanel" + str(len(parent.findChildren(DistanceBoxPanel)))) self.distanceUnit = distanceUnit self.distanceUnit1 = distanceUnit1 self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) self.frameBoxPanelIn = QFrame(self.frameBoxPanel) self.frameBoxPanelIn.setFrameShape(QFrame.StyledPanel) self.frameBoxPanelIn.setFrameShadow(QFrame.Raised) self.frameBoxPanelIn.setObjectName(("frameBoxPanelIn")) self.hLayoutframeBoxPanelIn = QHBoxLayout(self.frameBoxPanelIn) self.hLayoutframeBoxPanelIn.setSpacing(0) self.hLayoutframeBoxPanelIn.setMargin(0) self.hLayoutframeBoxPanelIn.setObjectName(("hLayoutframeBoxPanelIn")) self.txtDistance = QLineEdit(self.frameBoxPanelIn) self.txtDistance.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.txtDistance.setFont(font) self.txtDistance.setObjectName(self.objectName() + "_txtDistance") self.txtDistance.setText("0.0") self.txtDistance.setMinimumWidth(70) self.txtDistance.setMaximumWidth(70) self.hLayoutframeBoxPanelIn.addWidget(self.txtDistance) if self.distanceUnit1 != None: labelM = QLabel(self.frameBoxPanelIn) labelM.setObjectName(("labelM")) value = "" if self.distanceUnit == DistanceUnits.NM: value = " nm " elif self.distanceUnit == DistanceUnits.M: value = " m " elif self.distanceUnit == DistanceUnits.KM: value = " km " elif self.distanceUnit == DistanceUnits.FT: value = " ft " elif self.distanceUnit == DistanceUnits.MM: value = " mm " else: value = "" labelM.setText(value) self.hLayoutframeBoxPanelIn.addWidget(labelM) self.txtDistance1 = QLineEdit(self.frameBoxPanelIn) self.txtDistance1.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.txtDistance1.setFont(font) self.txtDistance1.setObjectName(self.objectName() + "_txtDistance1") self.txtDistance1.setText("0.0") self.txtDistance1.setMinimumWidth(70) self.txtDistance1.setMaximumWidth(70) self.txtDistance1.setText("0.0") self.hLayoutframeBoxPanelIn.addWidget(self.txtDistance1) label1 = QLabel(self.frameBoxPanelIn) label1.setObjectName(("labelFt")) value = "" if self.distanceUnit1 == DistanceUnits.NM: value = " nm " elif self.distanceUnit1 == DistanceUnits.M: value = " m " elif self.distanceUnit1 == DistanceUnits.KM: value = " km " elif self.distanceUnit1 == DistanceUnits.FT: value = " ft " elif self.distanceUnit1 == DistanceUnits.MM: value = " mm " else: value = "" label1.setText(value) self.hLayoutframeBoxPanelIn.addWidget(label1) # self.txtDistance.textChanged.connect(self.txtDistanceChanged) self.txtDistance1.textChanged.connect(self.txtDistance1Changed) self.txtDistance1.editingFinished.connect( self.txtDistanceEditingFinished) self.btnCaptureDistance = QToolButton(self.frameBoxPanelIn) self.btnCaptureDistance.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")), QIcon.Normal, QIcon.Off) self.btnCaptureDistance.setIcon(icon) self.btnCaptureDistance.setObjectName(("btnDegreeBoxPanel")) self.hLayoutframeBoxPanelIn.addWidget(self.btnCaptureDistance) self.hLayoutframeBoxPanel.addWidget(self.frameBoxPanelIn) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutBoxPanel.addItem(spacerItem) self.txtDistance.textChanged.connect(self.txtDistanceChanged) self.txtDistance.editingFinished.connect( self.txtDistanceEditingFinished) self.btnCaptureDistance.clicked.connect(self.btnCaptureDistanceClicked) # self.value = 0.0 self.flag = 0 self.txtDistance.setText("0.0")
def setPixmap(self, pixmap): if self._pixmap != pixmap: self._pixmap = QPixmap(pixmap) self.updateGeometry()
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_list.append(full_path) 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) self.controller.show_warning(message, context_name='ui_message') # 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_widgetExtended = [] self.list_labels = [] for i in range(0, 9): # Set image to QLabel pixmap = QPixmap(str(self.img_path_list[0][i])) pixmap = pixmap.scaled(171, 151, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) widget_name = "img_" + str(i) widget = self.dlg_gallery.findChild(QLabel, widget_name) # Set QLabel like ExtendedQLabel(ClickableLabel) self.widget_extended = ExtendedQLabel.ExtendedQLabel(widget) self.widget_extended.setPixmap(pixmap) self.start_indx = 0 # Set signal of ClickableLabel #self.dlg_gallery.connect(self.widget_extended, SIGNAL('clicked()'), (partial(self.zoom_img,i))) self.widget_extended.clicked.connect(partial(self.zoom_img, i)) self.list_widgetExtended.append(self.widget_extended) 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.dlg_gallery.exec_()
def get_desktop_pixmap(): return QPixmap.grabWindow(get_desktop().winId())
class OWParallelGraph(OWPlot, ScaleData): show_distributions = Setting(False) show_attr_values = Setting(True) show_statistics = Setting(default=False) group_lines = Setting(default=False) number_of_groups = Setting(default=5) number_of_steps = Setting(default=30) use_splines = Setting(False) alpha_value = Setting(150) alpha_value_2 = Setting(150) def __init__(self, widget, parent=None, name=None): OWPlot.__init__(self, parent, name, axes=[], widget=widget) ScaleData.__init__(self) self.update_antialiasing(False) self.widget = widget self.last_selected_curve = None self.enableGridXB(0) self.enableGridYL(0) self.domain_contingencies = None self.auto_update_axes = 1 self.old_legend_keys = [] self.selection_conditions = {} self.attributes = [] self.visualized_mid_labels = [] self.attribute_indices = [] self.valid_data = [] self.groups = {} self.selected_examples = [] self.unselected_examples = [] self.bottom_pixmap = QPixmap( gui.resource_filename("icons/upgreenarrow.png")) self.top_pixmap = QPixmap( gui.resource_filename("icons/downgreenarrow.png")) def set_data(self, data, subset_data=None, **args): self.start_progress() self.set_progress(1, 100) self.data = data self.have_data = True self.domain_contingencies = None self.groups = {} OWPlot.setData(self, data) ScaleData.set_data(self, data, no_data=True, **args) self.end_progress() def update_data(self, attributes, mid_labels=None): old_selection_conditions = self.selection_conditions self.clear() if not (self.have_data): return if len(attributes) < 2: return if self.show_statistics: self.alpha_value = TRANSPARENT self.alpha_value_2 = VISIBLE else: self.alpha_value = VISIBLE self.alpha_value_2 = TRANSPARENT self.attributes = attributes self.attribute_indices = [ self.attribute_name_index[name] for name in self.attributes ] self.valid_data = self.get_valid_list(self.attribute_indices) self.visualized_mid_labels = mid_labels self.add_relevant_selections(old_selection_conditions) if self.data_has_discrete_class: self.discrete_palette.set_number_of_colors( len(self.data_domain.class_var.values)) if self.group_lines: self.show_statistics = False self.draw_groups() else: self.show_statistics = False self.draw_curves() self.draw_distributions() self.draw_axes() self.draw_statistics() self.draw_mid_labels(mid_labels) self.draw_legend() self.replot() def add_relevant_selections(self, old_selection_conditions): """Keep only conditions related to the currently visualized attributes""" for name, value in old_selection_conditions.items(): if name in self.attributes: self.selection_conditions[name] = value def draw_axes(self): self.remove_all_axes() for i in range(len(self.attributes)): axis_id = UserAxis + i a = self.add_axis(axis_id, line=QLineF(i, 0, i, 1), arrows=AxisStart | AxisEnd, zoomable=True) a.always_horizontal_text = True a.max_text_width = 100 a.title_margin = -10 a.text_margin = 0 a.setZValue(5) self.set_axis_title(axis_id, self.data_domain[self.attributes[i]].name) self.set_show_axis_title(axis_id, self.show_attr_values) if self.show_attr_values: attr = self.data_domain[self.attributes[i]] if attr.is_continuous: self.set_axis_scale(axis_id, self.attr_values[attr.name][0], self.attr_values[attr.name][1]) elif attr.is_discrete: attribute_values = get_variable_values_sorted( self.data_domain[self.attributes[i]]) attr_len = len(attribute_values) values = [ float(1.0 + 2.0 * j) / float(2 * attr_len) for j in range(len(attribute_values)) ] a.set_bounds((0, 1)) self.set_axis_labels(axis_id, labels=attribute_values, values=values) def draw_curves(self): conditions = { name: self.attributes.index(name) for name in self.selection_conditions.keys() } def is_selected(example): return all(self.selection_conditions[name][0] <= example[index] <= self.selection_conditions[name][1] for (name, index) in list(conditions.items())) selected_curves = defaultdict(list) background_curves = defaultdict(list) diff, mins = [], [] for i in self.attribute_indices: var = self.data_domain[i] if var.is_discrete: diff.append(len(var.values)) mins.append(-0.5) else: diff.append( self.domain_data_stat[i].max - self.domain_data_stat[i].min or 1) mins.append(self.domain_data_stat[i].min) def scale_row(row): return [(x - m) / d for x, m, d in zip(row, mins, diff)] for row_idx, row in enumerate(self.data[:, self.attribute_indices]): if any(np.isnan(v) for v in row.x): continue color = tuple(self.select_color(row_idx)) if is_selected(row): color += (self.alpha_value, ) selected_curves[color].extend(scale_row(row)) self.selected_examples.append(row_idx) else: color += (self.alpha_value_2, ) background_curves[color].extend(row) self.unselected_examples.append(row_idx) self._draw_curves(selected_curves) self._draw_curves(background_curves) def select_color(self, row_index): if self.data_has_class: if self.data_has_continuous_class: return self.continuous_palette.getRGB( self.data[row_index, self.data_class_index]) else: return self.discrete_palette.getRGB( self.data[row_index, self.data_class_index]) else: return 0, 0, 0 def _draw_curves(self, selected_curves): n_attr = len(self.attributes) for color, y_values in sorted(selected_curves.items()): n_rows = int(len(y_values) / n_attr) x_values = list(range(n_attr)) * n_rows curve = OWCurve() curve.set_style(OWCurve.Lines) curve.set_color(QColor(*color)) curve.set_segment_length(n_attr) curve.set_data(x_values, y_values) curve.attach(self) def draw_groups(self): phis, mus, sigmas = self.compute_groups() diff, mins = [], [] for i in self.attribute_indices: var = self.data_domain[i] if var.is_discrete: diff.append(len(var.values)) mins.append(-0.5) else: diff.append( self.domain_data_stat[i].max - self.domain_data_stat[i].min or 1) mins.append(self.domain_data_stat[i].min) for j, (phi, cluster_mus, cluster_sigma) in enumerate(zip(phis, mus, sigmas)): for i, (mu1, sigma1, mu2, sigma2), in enumerate( zip(cluster_mus, cluster_sigma, cluster_mus[1:], cluster_sigma[1:])): nmu1 = (mu1 - mins[i]) / diff[i] nmu2 = (mu2 - mins[i + 1]) / diff[i + 1] nsigma1 = math.sqrt(sigma1) / diff[i] nsigma2 = math.sqrt(sigma2) / diff[i + 1] polygon = ParallelCoordinatePolygon( i, nmu1, nmu2, nsigma1, nsigma2, phi, tuple(self.discrete_palette.getRGB(j))) polygon.attach(self) self.replot() def compute_groups(self): key = (tuple(self.attributes), self.number_of_groups, self.number_of_steps) if key not in self.groups: def callback(i, n): self.set_progress(i, 2 * n) conts = create_contingencies(self.data[:, self.attribute_indices], callback=callback) self.set_progress(50, 100) w, mu, sigma, phi = lac(conts, self.number_of_groups, self.number_of_steps) self.set_progress(100, 100) self.groups[key] = list(map(np.nan_to_num, (phi, mu, sigma))) return self.groups[key] def draw_legend(self): if self.data_has_class: if self.data_domain.has_discrete_class: self.legend().clear() values = get_variable_values_sorted(self.data_domain.class_var) for i, value in enumerate(values): self.legend().add_item( self.data_domain.class_var.name, value, OWPoint(OWPoint.Rect, self.discrete_palette[i], self.point_width)) else: values = self.attr_values[self.data_domain.class_var.name] decimals = self.data_domain.class_var.number_of_decimals self.legend().add_color_gradient( self.data_domain.class_var.name, ["%%.%df" % decimals % v for v in values]) else: self.legend().clear() self.old_legend_keys = [] def draw_mid_labels(self, mid_labels): if mid_labels: for j in range(len(mid_labels)): self.addMarker(mid_labels[j], j + 0.5, 1.0, alignment=Qt.AlignCenter | Qt.AlignTop) def draw_statistics(self): """Draw lines that represent standard deviation or quartiles""" return # TODO: Implement using BasicStats if self.show_statistics and self.have_data: data = [] for attr_idx in self.attribute_indices: if not self.data_domain[attr_idx].is_continuous: data.append([()]) continue # only for continuous attributes if not self.data_has_class or self.data_has_continuous_class: # no class if self.show_statistics == MEANS: m = self.domain_data_stat[attr_idx].mean dev = self.domain_data_stat[attr_idx].var data.append([(m - dev, m, m + dev)]) elif self.show_statistics == MEDIAN: data.append([(0, 0, 0)]) continue sorted_array = np.sort(attr_values) if len(sorted_array) > 0: data.append([ (sorted_array[int(len(sorted_array) / 4.0)], sorted_array[int(len(sorted_array) / 2.0)], sorted_array[int(len(sorted_array) * 0.75)]) ]) else: data.append([(0, 0, 0)]) else: curr = [] class_values = get_variable_values_sorted( self.data_domain.class_var) for c in range(len(class_values)): attr_values = self.data[ attr_idx, self.data[self.data_class_index] == c] attr_values = attr_values[~np.isnan(attr_values)] if len(attr_values) == 0: curr.append((0, 0, 0)) continue if self.show_statistics == MEANS: m = attr_values.mean() dev = attr_values.std() curr.append((m - dev, m, m + dev)) elif self.show_statistics == MEDIAN: sorted_array = np.sort(attr_values) curr.append( (sorted_array[int(len(attr_values) / 4.0)], sorted_array[int(len(attr_values) / 2.0)], sorted_array[int(len(attr_values) * 0.75)])) data.append(curr) # draw vertical lines for i in range(len(data)): for c in range(len(data[i])): if data[i][c] == (): continue x = i - 0.03 * (len(data[i]) - 1) / 2.0 + c * 0.03 col = QColor(self.discrete_palette[c]) col.setAlpha(self.alpha_value_2) self.add_curve( "", col, col, 3, OWCurve.Lines, OWPoint.NoSymbol, xData=[x, x, x], yData=[data[i][c][0], data[i][c][1], data[i][c][2]], lineWidth=4) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03], yData=[data[i][c][0], data[i][c][0]], lineWidth=4) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03], yData=[data[i][c][1], data[i][c][1]], lineWidth=4) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03], yData=[data[i][c][2], data[i][c][2]], lineWidth=4) # draw lines with mean/median values if not self.data_has_class or self.data_has_continuous_class: class_count = 1 else: class_count = len(self.data_domain.class_var.values) for c in range(class_count): diff = -0.03 * (class_count - 1) / 2.0 + c * 0.03 ys = [] xs = [] for i in range(len(data)): if data[i] != [()]: ys.append(data[i][c][1]) xs.append(i + diff) else: if len(xs) > 1: col = QColor(self.discrete_palette[c]) col.setAlpha(self.alpha_value_2) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=xs, yData=ys, lineWidth=4) xs = [] ys = [] col = QColor(self.discrete_palette[c]) col.setAlpha(self.alpha_value_2) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=xs, yData=ys, lineWidth=4) def draw_distributions(self): """Draw distributions with discrete attributes""" if not (self.show_distributions and self.have_data and self.data_has_discrete_class): return class_count = len(self.data_domain.class_var.values) class_ = self.data_domain.class_var # we create a hash table of possible class values (happens only if we have a discrete class) if self.domain_contingencies is None: self.domain_contingencies = dict( zip([attr for attr in self.data_domain if attr.is_discrete], get_contingencies(self.raw_data, skipContinuous=True))) self.domain_contingencies[class_] = get_contingency( self.raw_data, class_, class_) max_count = max([ contingency.max() for contingency in self.domain_contingencies.values() ] or [1]) sorted_class_values = get_variable_values_sorted( self.data_domain.class_var) for axis_idx, attr_idx in enumerate(self.attribute_indices): attr = self.data_domain[attr_idx] if attr.is_discrete: continue contingency = self.domain_contingencies[attr] attr_len = len(attr.values) # we create a hash table of variable values and their indices sorted_variable_values = get_variable_values_sorted(attr) # create bar curve for j in range(attr_len): attribute_value = sorted_variable_values[j] value_count = contingency[:, attribute_value] for i in range(class_count): class_value = sorted_class_values[i] color = QColor(self.discrete_palette[i]) color.setAlpha(self.alpha_value) width = float( value_count[class_value] * 0.5) / float(max_count) y_off = float(1.0 + 2.0 * j) / float(2 * attr_len) height = 0.7 / float(class_count * attr_len) y_low_bottom = y_off + float( class_count * height) / 2.0 - i * height curve = PolygonCurve(QPen(color), QBrush(color), xData=[ axis_idx, axis_idx + width, axis_idx + width, axis_idx ], yData=[ y_low_bottom, y_low_bottom, y_low_bottom - height, y_low_bottom - height ], tooltip=attr.name) curve.attach(self) # handle tooltip events def event(self, ev): if ev.type() == QEvent.ToolTip: x = self.inv_transform(xBottom, ev.pos().x()) y = self.inv_transform(yLeft, ev.pos().y()) canvas_position = self.mapToScene(ev.pos()) x_float = self.inv_transform(xBottom, canvas_position.x()) contact, (index, pos) = self.testArrowContact(int(round(x_float)), canvas_position.x(), canvas_position.y()) if contact: attr = self.data_domain[self.attributes[index]] if attr.is_continuous: condition = self.selection_conditions.get( attr.name, [0, 1]) val = self.attr_values[attr.name][0] + condition[pos] * ( self.attr_values[attr.name][1] - self.attr_values[attr.name][0]) str_val = attr.name + "= %%.%df" % attr.number_of_decimals % val QToolTip.showText(ev.globalPos(), str_val) else: for curve in self.items(): if type(curve) == PolygonCurve and \ curve.boundingRect().contains(x, y) and \ getattr(curve, "tooltip", None): (name, value, total, dist) = curve.tooltip count = sum([v[1] for v in dist]) if count == 0: continue tooltip_text = "Attribute: <b>%s</b><br>Value: <b>%s</b><br>" \ "Total instances: <b>%i</b> (%.1f%%)<br>" \ "Class distribution:<br>" % ( name, value, count, 100.0 * count / float(total)) for (val, n) in dist: tooltip_text += " <b>%s</b> : <b>%i</b> (%.1f%%)<br>" % ( val, n, 100.0 * float(n) / float(count)) QToolTip.showText(ev.globalPos(), tooltip_text[:-4]) elif ev.type() == QEvent.MouseMove: QToolTip.hideText() return OWPlot.event(self, ev) def testArrowContact(self, indices, x, y): if type(indices) != list: indices = [indices] for index in indices: if index >= len(self.attributes) or index < 0: continue int_x = self.transform(xBottom, index) bottom = self.transform( yLeft, self.selection_conditions.get(self.attributes[index], [0, 1])[0]) bottom_rect = QRect(int_x - self.bottom_pixmap.width() / 2, bottom, self.bottom_pixmap.width(), self.bottom_pixmap.height()) if bottom_rect.contains(QPoint(x, y)): return 1, (index, 0) top = self.transform( yLeft, self.selection_conditions.get(self.attributes[index], [0, 1])[1]) top_rect = QRect(int_x - self.top_pixmap.width() / 2, top - self.top_pixmap.height(), self.top_pixmap.width(), self.top_pixmap.height()) if top_rect.contains(QPoint(x, y)): return 1, (index, 1) return 0, (0, 0) def mousePressEvent(self, e): canvas_position = self.mapToScene(e.pos()) x = self.inv_transform(xBottom, canvas_position.x()) contact, info = self.testArrowContact(int(round(x)), canvas_position.x(), canvas_position.y()) if contact: self.pressed_arrow = info else: OWPlot.mousePressEvent(self, e) def mouseMoveEvent(self, e): if hasattr(self, "pressed_arrow"): canvas_position = self.mapToScene(e.pos()) y = min(1, max(0, self.inv_transform(yLeft, canvas_position.y()))) index, pos = self.pressed_arrow attr = self.data_domain[self.attributes[index]] old_condition = self.selection_conditions.get(attr.name, [0, 1]) old_condition[pos] = y self.selection_conditions[attr.name] = old_condition self.update_data(self.attributes, self.visualized_mid_labels) if attr.is_continuous: val = self.attr_values[attr.name][0] + old_condition[pos] * ( self.attr_values[attr.name][1] - self.attr_values[attr.name][0]) strVal = attr.name + "= %.2f" % val QToolTip.showText(e.globalPos(), strVal) if self.sendSelectionOnUpdate and self.auto_send_selection_callback: self.auto_send_selection_callback() else: OWPlot.mouseMoveEvent(self, e) def mouseReleaseEvent(self, e): if hasattr(self, "pressed_arrow"): del self.pressed_arrow else: OWPlot.mouseReleaseEvent(self, e) def zoom_to_rect(self, r): r.setTop(self.graph_area.top()) r.setBottom(self.graph_area.bottom()) super().zoom_to_rect(r) def removeAllSelections(self, send=1): self.selection_conditions = {} self.update_data(self.attributes, self.visualized_mid_labels) # draw the curves and the selection conditions def drawCanvas(self, painter): OWPlot.drawCanvas(self, painter) for i in range( int( max( 0, math.floor( self.axisScaleDiv( xBottom).interval().minValue()))), int( min( len(self.attributes), math.ceil( self.axisScaleDiv(xBottom).interval().maxValue()) + 1))): bottom, top = self.selection_conditions.get( self.attributes[i], (0, 1)) painter.drawPixmap( self.transform(xBottom, i) - self.bottom_pixmap.width() / 2, self.transform(yLeft, bottom), self.bottom_pixmap) painter.drawPixmap( self.transform(xBottom, i) - self.top_pixmap.width() / 2, self.transform(yLeft, top) - self.top_pixmap.height(), self.top_pixmap) def auto_send_selection_callback(self): pass def clear(self): super().clear() self.attributes = [] self.visualized_mid_labels = [] self.selected_examples = [] self.unselected_examples = [] self.selection_conditions = {}
def __init__(self, parent): QDialog.__init__(self, parent) palette = QPalette(); brush = QBrush(QColor(255, 255, 255, 255)); brush.setStyle(Qt.SolidPattern); palette.setBrush(QPalette.Active, QPalette.Base, brush); palette.setBrush(QPalette.Active, QPalette.Window, brush); palette.setBrush(QPalette.Inactive, QPalette.Base, brush); palette.setBrush(QPalette.Inactive, QPalette.Window, brush); palette.setBrush(QPalette.Disabled, QPalette.Base, brush); palette.setBrush(QPalette.Disabled, QPalette.Window, brush); self.setPalette(palette); self.ui = Ui_FlightPlannerBase() self.ui.setupUi(self) self.newDlgExisting = False self.chbHideCloseInObst = QCheckBox(self.ui.grbResult) font = QFont() font.setBold(False) font.setWeight(50) self.chbHideCloseInObst.setFont(font) self.chbHideCloseInObst.setObjectName("chbHideCloseInObst") self.ui.vlResultGroup.addWidget(self.chbHideCloseInObst) self.chbHideCloseInObst.setText("Hide close-in obstacles") self.chbHideCloseInObst.setVisible(False) self.ui.tblHistory.setSelectionBehavior(1) # self.ui.tabCtrlGeneral.setTabsClosable(True) self.ui.btnUpdateQA.setVisible(False) self.ui.btnUpdateQA_2.setVisible(False) ''' combo boxes event ''' self.ui.cmbObstSurface.currentIndexChanged.connect(self.cmbObstSurfaceChanged) self.ui.cmbUnits.currentIndexChanged.connect(self.changeResultUnit) ''' buttons clicked connect ''' self.ui.btnClose.clicked.connect(self.reject) self.ui.btnClose_2.clicked.connect(self.reject) self.ui.btnHistoryClose.clicked.connect(self.reject) self.ui.btnConstruct.clicked.connect(self.btnConstruct_Click) self.ui.btnEvaluate.clicked.connect(self.btnEvaluate_Click) self.ui.btnOpenData.clicked.connect(self.openData) self.ui.btnSaveData.clicked.connect(self.saveData) self.ui.btnPDTCheck.clicked.connect(self.btnPDTCheck_Click) self.ui.btnExportResult.clicked.connect(self.exportResult) self.ui.tblHistory.clicked.connect(self.tblHistory_Click) self.ui.btnUpdateQA.clicked.connect(self.btnUpdateQA_Click) self.ui.btnUpdateQA_2.clicked.connect(self.btnUpdateQA_2_Click) self.ui.btnCriticalLocate.clicked.connect(self.criticalLocate) self.connect(self.ui.tblObstacles, SIGNAL("tableViewObstacleMouseReleaseEvent_rightButton"), self.tableViewObstacleMouseTeleaseEvent_rightButton) self.connect(self.ui.tblObstacles, SIGNAL("pressedEvent"), self.tblObstacles_pressed) ''' properties ''' self.parametersPanel = None self.obstaclesModel = None self.surfaceType = "" self.surfaceSubGroupNames = [] self.uiStateInit() self.obstacleTableInit() self.newDlgExisting = True self.resultColumnNames = [] self.stdItemModelHistory = QStandardItemModel() # self.stdItemModelHistory. self.ui.tblHistory.setModel(self.stdItemModelHistory) icon = QIcon() icon.addPixmap(QPixmap("Resource/btnImage/dlgIcon.png"), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.resultLayerList = [] self.symbolLayers = [] self.selectedObstacleMoselIndex = None self.changedCriticalObstacleValue = []
def setupScene(self): self.information(0) self.error(0) if self.data: attr = self.stringAttrs[self.imageAttr] titleAttr = self.allAttrs[self.titleAttr] instances = [inst for inst in self.data if numpy.isfinite(inst[attr])] widget = ThumbnailWidget() layout = widget.layout() self.scene.addItem(widget) for i, inst in enumerate(instances): url = self.urlFromValue(inst[attr]) title = str(inst[titleAttr]) thumbnail = GraphicsThumbnailWidget( QPixmap(), title=title, parent=widget ) thumbnail.setToolTip(url.toString()) thumbnail.instance = inst layout.addItem(thumbnail, i / 5, i % 5) if url.isValid(): future = self.loader.get(url) watcher = _FutureWatcher(parent=thumbnail) # watcher = FutureWatcher(future, parent=thumbnail) def set_pixmap(thumb=thumbnail, future=future): if future.cancelled(): return if future.exception(): # Should be some generic error image. pixmap = QPixmap() thumb.setToolTip(thumb.toolTip() + "\n" + str(future.exception())) else: pixmap = QPixmap.fromImage(future.result()) thumb.setPixmap(pixmap) if not pixmap.isNull(): thumb.setThumbnailSize(self.pixmapSize(pixmap)) self._updateStatus(future) watcher.finished.connect(set_pixmap, Qt.QueuedConnection) watcher.setFuture(future) else: future = None self.items.append(_ImageItem(i, thumbnail, url, future)) widget.show() widget.geometryChanged.connect(self._updateSceneRect) self.info.setText("Retrieving...\n") self.thumbnailWidget = widget self.sceneLayout = layout if self.sceneLayout: width = (self.sceneView.width() - self.sceneView.verticalScrollBar().width()) self.thumbnailWidget.reflow(width) self.thumbnailWidget.setPreferredWidth(width) self.sceneLayout.activate()
def initUI(self): self.main_frame = QtGui.QWidget() self.setWindowIcon(QtGui.QIcon("Icon.jpg")) # 菜单 ope = QtGui.QAction(QtGui.QIcon('Icon.jpg'), '打开', self) self.connect(ope, QtCore.SIGNAL('triggered()'), self.showDialogFile) clos = QtGui.QAction(QtGui.QIcon("Icon.jpg"), '关闭', self) self.connect(clos, QtCore.SIGNAL('triggered()'), self.close) sett = QtGui.QAction(QtGui.QIcon("Ioon.jpg"), '配置', self) self.connect(sett, QtCore.SIGNAL('triggered()'), self.showDialogConf) help = QtGui.QAction(QtGui.QIcon("Icon.jpg"), '作者', self) self.connect(help, QtCore.SIGNAL('triggered()'), self.showDialogHelp) # 添加菜单栏 menubar = self.menuBar() file = menubar.addMenu('文件') file.addAction(ope) file.addAction(clos) setting = menubar.addMenu('配置') setting.addAction(sett) helpp = menubar.addMenu('帮助') helpp.addAction(help) #添加功能按钮 analyButton = QtGui.QPushButton("分析", self) analyButton.setFixedSize(100,50) bigButton = QtGui.QPushButton("放大", self) bigButton.setFixedSize(100,50) smallButton = QtGui.QPushButton("缩小", self) smallButton.setFixedSize(100,50) adaptButton = QtGui.QPushButton("缩放合适大小", self) adaptButton.setFixedSize(100,50) #定义和绑定退出动作 quitButton = QtGui.QPushButton("退出", self) quitButton.clicked.connect(self.onClickQuit) quitButton.setFixedSize(100,50) picWedget = QtGui.QLabel(self) picWedget.setPixmap(QPixmap("building.png")) picWedget.setGeometry(0, 50, 900, 675) #定义主界面布局 vbox2 = QtGui.QVBoxLayout() vbox2.addWidget(analyButton) # vbox2.setStretchFactor(analyButton) vbox2.addWidget(bigButton) vbox2.addWidget(smallButton) vbox2.addWidget(adaptButton) vbox2.addWidget(quitButton) vbox2.addStretch(1) hbox2 = QtGui.QHBoxLayout() hbox2.addWidget(picWedget) hbox2.addLayout(vbox2) hbox2.addStretch(1) #加载页面配置 self.main_frame.setLayout(hbox2) self.setCentralWidget(self.main_frame) self.setGeometry(300, 200, 1080, 800) self.setWindowTitle('交互式移动通信网络分析和规划') self.show()
def show_fullscreen_image(self, image): """:param image: a QImage""" pixmap = QPixmap.fromImage(image) self.show_fullscreen_pixmap(pixmap)
def __init__(self, *args): abstractPixmapScene.__init__(self, img=QPixmap("sprites/calle/centro.png"))
def set_widgets(self): """Set widgets on the Aggregation Layer From Browser tab.""" self.tvBrowserAggregation_selection_changed() # Set icon self.lblIconIFCWAggregationFromBrowser.setPixmap(QPixmap(None))
def icon(self): return QIcon(QPixmap(16, 16))
def save_capture(self, filename): """Saves the current capture and its annotations to the given file.""" pixmap = QPixmap(self.window.center_view.size()) self.window.center_view.render(pixmap) pixmap.save(filename)
def pixmap(self): return QPixmap.fromImage(self.image)
def __init__(self, parent=None, autoupdate=Event()): QWidget.__init__(self, parent) # self.app = QApplication(sys.argv) # window = QMainWindow() self.my_gauge = Ui_MainWindow() self.my_gauge.setupUi(self) self.maxButton_NameTextLenght = 15 # Max charcters # self.my_gauge.name_list.setFont() self.my_gauge.widget.enable_barGraph = True self.my_gauge.widget.value_needle_snapzone = 1 self.my_gauge.widget.set_scale_polygon_colors([[.0, Qt.green], [.1, Qt.green], [.25, Qt.yellow], [.55, Qt.blue], [.95, Qt.darkBlue]]) # self.my_gauge.ActualSlider.setMaximum(self.my_gauge.widget.value_max) # self.my_gauge.ActualSlider.setMinimum(self.my_gauge.widget.value_min) # self.my_gauge.AussenRadiusSlider.setValue(self.my_gauge.widget.gauge_color_outer_radius_factor * 1000) # self.my_gauge.InnenRadiusSlider.setValue(self.my_gauge.widget.gauge_color_inner_radius_factor * 1000) # self.my_gauge.GaugeStartSlider.setValue(self.my_gauge.widget.scale_angle_start_value) # self.my_gauge.GaugeSizeSlider.setValue(self.my_gauge.widget.scale_angle_size) self.my_gauge.pushButton.clicked.connect(self.start_timer) self.my_gauge.pushButton_openfile.clicked.connect( self.openfile_read_list) self.my_gauge.pushButton_clear.clicked.connect( self.clear_name_list_widget) self.my_gauge.name_list.itemSelectionChanged.connect( self.item_selection_changed) self.my_gauge.checkBox_toggle_info.stateChanged.connect( self.toggle_info) # self.my_gauge.widge self.my_gauge.widget.set_enable_ScaleText(False) self.autoupdate = autoupdate self.starten = Event() self.stoppen = Event() self.new_data = Queue() self.reset = Event() self.my_queue = Queue() button_x_size = 30 button_y_size = 30 x_pos = 20 y_pos = 0 self.button_ring = (QPushButton(str("sec"), self)) self.button_ring.setGeometry(x_pos, y_pos, button_x_size, button_y_size) self.button_ring.clicked.connect(self.set_timer_seconds) self.button_ring.move(x_pos - button_x_size / 2, y_pos) # + button_y_size / 2) self.button_ring.show() self.button_panel = (QPushButton(str(">"), self)) self.button_panel.setGeometry(x_pos + button_x_size, y_pos, button_x_size, button_y_size) self.button_panel.clicked.connect(self.toggle_panel) self.button_panel.move((x_pos - button_x_size / 2) + button_x_size, y_pos) # + button_y_size / 2) self.button_panel.show() text_x_size = 500 text_y_size = 75 self.name_highlight = QLabel(self) self.name_highlight.setGeometry(x_pos + (button_x_size * 2), 0, text_x_size, text_y_size) self.name_highlight.move(x_pos + button_x_size * 2 - button_x_size / 2, -20) # self.name_highlight.setGeometry(30, 30, text_x_size, text_y_size) # self.name_highlight.move(70, -10) self.name_highlight.setText("") myfont = QFont("Segoe UI", 30) myfont.setBold(True) self.name_highlight.setFont(myfont) self.name_highlight.show() self.panel_show = True # self.toggle_button_label_info = False self.toggle_button_label_info = self.my_gauge.checkBox_toggle_info.checkState( ) # self.toggle_info() self.toggle_show_name_label() self.my_gauge.checkBox_show_name_label.stateChanged.connect( self.toggle_show_name_label) self.running = sut(self.starten, self.stoppen, self.reset, self.my_queue, self.new_data) self.running.start() self.set_time(30) time.sleep(0.1) # self.starten.set() self.state_dict = { "init": "start", "reset": "start", "start": "stop", "stop": "reset" } self.actual_state = "init" print(self.actual_state) # add banner image banner_name = "banner.png" banner_path = os.path.dirname(__file__) + os.path.sep + banner_name self.pixmap = QPixmap(banner_path) # self.pixmap = self.pixmap.scaledToWidth(300) self.my_gauge.banner.setPixmap(self.pixmap) self.my_gauge.banner.setScaledContents(True) self.my_gauge.widget.initial_value_fontsize = 50 QTimer.singleShot(10, self.check_new_data) self.update() self.toggle_info()
def render_cell(self): self.log.info('render_cell') self.log.debug('self.current_sample_id: %d' % self.current_sample_id) if len(self.samples) == 0: raise Exception('no samples to show!') sample = [ s for s in self.samples if s['id'] == self.current_sample_id ][0] cell = sample['cell'] nucleus = sample['nucleus'] self.renderingMutex.lock() if self.renderingThread.isRunning(): self.log.debug('terminating rendering thread') self.renderingThread.quit() else: self.renderingThread.setIndividual(self.current_sample_id, sample) self.trigger_render() self.renderingMutex.unlock() c, r = nucleus.boundary.xy r_n, c_n = draw.polygon(r, c) self.log.debug('feat id: %d' % sample['id']) self.mplEduHist.hide() self.imgEdu.clear() self.imgCell.clear() self.imgPericentrin.clear() self.imgTubulin.clear() self.lblEduMin.setText('min ' + m.eng_string( self.edu[r_n, c_n].min(), format='%0.1f', si=True)) self.lblEduMax.setText('max ' + m.eng_string( self.edu[r_n, c_n].max(), format='%0.1f', si=True)) self.lblEduAvg.setText('avg ' + m.eng_string( self.edu[r_n, c_n].mean(), format='%0.1f', si=True)) self.lblTubMin.setText('min ' + m.eng_string( self.tubulin[r_n, c_n].min(), format='%0.1f', si=True)) self.lblTubMax.setText('max ' + m.eng_string( self.tubulin[r_n, c_n].max(), format='%0.1f', si=True)) self.lblTubAvg.setText('avg ' + m.eng_string( self.tubulin[r_n, c_n].mean(), format='%0.1f', si=True)) self.lblCentr_n.setText( '%d' % len([s for s in sample['centrosomes'] if s is not None])) self.lblId.setText('id %d' % sample['id']) # self.lblOK.setText('OK' if valid else 'no OK') fig = Figure((self.imgCentrCloseup.width() / mydpi, self.imgCentrCloseup.height() / mydpi), subplotpars=sp, dpi=mydpi) canvas = FigureCanvas(fig) ax = fig.gca() ax.set_aspect('equal') ax.set_axis_off() l, b, w, h = fig.bbox.bounds c1 = sample['centrosomes'][0]['pt'] c2 = sample['centrosomes'][1]['pt'] self.lblDist_nc.setText('%0.2f' % nucleus.centroid.distance(c1)) self.lblDist_nb.setText('%0.2f' % nucleus.exterior.distance(c1)) self.lblDist_cc.setText('%0.2f' % cell.centroid.distance(c1)) self.lblDist_cb.setText('%0.2f' % cell.exterior.distance(c1)) ax.imshow(self.pericentrin, cmap='gray') if c1 is not None: c = plt.Circle((c1.x, c1.y), radius=5, facecolor='none', edgecolor='r', linestyle='--', linewidth=1, zorder=5) ax.add_artist(c) if c2 is not None: c = plt.Circle((c2.x, c2.y), radius=5, facecolor='none', edgecolor='b', linestyle='--', linewidth=1, zorder=5) ax.add_artist(c) ax.set_xlim(c1.x - w / 8, c1.x + w / 8) ax.set_ylim(c1.y - h / 8, c1.y + h / 8) qimg_closeup = ImageQt(utils.canvas_to_pil(canvas)) self.imgCentrCloseup.setPixmap(QPixmap.fromImage(qimg_closeup)) self.update()
def __init__(self, parent=None): super(ToggleEye, self).__init__(parent=parent) self._active = True self._eye_open = QPixmap(":icons/icons/stock-eye-20.png") self._eye_closed = QPixmap(":icons/icons/stock-eye-20-gray.png") self.setPixmap(self._eye_open)
def setImage3(self, image): self.videoCom3.setPixmap(QPixmap.fromImage(image))
res[i, j] = (a == kn).all() return res kernel = cv2.imread("pt.png", 0) kernel = kernel[430:460, 696:710] m = PyMouse() app = QApplication(sys.argv) # w = gtk.gdk.get_default_root_window() # sz = w.get_size() while (True): # pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1]) # pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1]) # pb.save("screenshot.png","png") QPixmap.grabWindow(QApplication.desktop().winId()).save( 'screenshot.png', 'png') screenshot = cv2.imread("screenshot.png", 0) # # kernel = screenshot[430:460, 696:710] # plt.imshow(kernel) # plt.show() res = det(screenshot, kernel) x = max(np.argmax(res, 0)) y = max(np.argmax(res, 1)) if x + y: # k = PyKeyboard() # x_dim, y_dim = m.screen_size() m.click(y, x, 1) # k.type_string('Hello, World!') time.sleep(30)