def initUI(self): path = "Image/" image = QPixmap(path + self.name + ".png") ButtonIcon = QIcon(image) self.setIcon(ButtonIcon) self.setIconSize(image.rect().size()) self.setFixedSize(image.rect().size())
def mouseMoveEvent(self, e: QtGui.QMouseEvent) -> None: if e.buttons() != Qt.LeftButton: return None #根据currentIndex获取数据行的名称 mimeData = QMimeData() currentRow = self.currentIndex().row() index = self.model().index(currentRow, 0) itemName = self.model().data(index) mimeData.setText('{}:{}:{}'.format(self.type, self.address, itemName)) #绘制拖动时的图像 width = self.columnWidth(0) height = self.rowHeight(currentRow) pixmap = QPixmap(width, height) paint = QPainter() paint.begin(pixmap) paint.fillRect(pixmap.rect(), QColor(Qt.white)) paint.drawRect(0, 0, width - 1, height - 1) paint.drawText(pixmap.rect(), Qt.AlignCenter, itemName) paint.end() #设定拖动项的数据和图标 drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.exec_(Qt.MoveAction) super().mouseMoveEvent(e)
def data(self, index=QModelIndex(), role=Qt.DisplayRole): if role not in [Qt.DecorationRole, Qt.EditRole]: return QVariant() if role == Qt.DecorationRole: img = None # solid special case if index.row() == 0: img = QPixmap(48, 48) img.fill(Qt.black) # pattern case else: img = self.patternImage.copy(48 * (index.row() - 1), 0, 48, 48) foreMask = img.createMaskFromColor(QColor(Qt.white)) backMask = img.createMaskFromColor(QColor(Qt.black)) p = QPainter(img) p.setPen(self.foreColor()) p.drawPixmap(img.rect(), foreMask, foreMask.rect()) p.setPen(self.backColor()) p.drawPixmap(img.rect(), backMask, backMask.rect()) p.end() return img elif role == Qt.EditRole: if index.row() == 0: return -2 # solid special case else: return index.row() return QVariant()
def __init__(self, link: Link, *args, **kwargs): super().__init__(*args, **kwargs) self.link = link layout = QHBoxLayout() pm_remove = QPixmap('imgs/close-thick.png') pm_remove_painter = QPainter(pm_remove) pm_remove_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) pm_remove_painter.fillRect(pm_remove.rect(), QColor(0, 102, 202)) pm_remove_painter.end() pic_remove = QLabel() pic_remove.mousePressEvent = self.on_remove pic_remove.setPixmap(pm_remove) layout.addWidget(pic_remove) if link.active: pm_switch = QPixmap('imgs/toggle-switch.png') else: pm_switch = QPixmap('imgs/toggle-switch-off.png') pm_switch_painter = QPainter(pm_switch) pm_switch_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) if link.active: pm_switch_painter.fillRect(pm_switch.rect(), QColor(0, 192, 0)) else: pm_switch_painter.fillRect(pm_switch.rect(), QColor(255, 64, 0)) pm_switch_painter.end() pic_switch = QLabel() pic_switch.mousePressEvent = self.on_switch pic_switch.setPixmap(pm_switch) layout.addWidget(pic_switch) self.setLayout(layout)
def add_button_highlight(self, title, redo=True): for button_info in self._buttons: if button_info.title == title: break else: return icon = button_info.icon if icon is None or icon.isNull(): # Make a single color icon pm = QPixmap(256, 256) pm.fill(self.highlight_color) else: sizes = icon.availableSizes() sizes.sort(key=lambda s: s.width()) pm = icon.pixmap(icon.actualSize(sizes[-1])) with QPainter(pm) as p: p.setCompositionMode(QPainter.CompositionMode_DestinationOver) if 1: # draw filled p.fillRect(pm.rect(), self.highlight_color) else: # draw outline r = pm.rect() pen_width = max(r.width(), r.height()) / 16 p.setPen(self.highlight_color) pen = p.pen() pen.setWidth(pen_width) p.setPen(pen) adj = pen_width / 2 p.drawRect(r.adjusted(adj, adj, -adj, -adj)) button_info.highlight_icon = QIcon(pm) if redo: self._redo_layout()
def set_table_icons(self, table_icon_list): """The list 'table_icon_list' contains tuples (file_name_short, marker_name, face, color) [description] Arguments: - table_icon_list {[type]} -- [description] """ self.DataSettreeWidget.blockSignals( True ) #avoid triggering 'itemChanged' signal that causes a call to do_plot() for fname, marker_name, face, color in table_icon_list: item = self.DataSettreeWidget.findItems( fname, Qt.MatchCaseSensitive, column=0) #returns list of items matching file name if item: #paint icon folder = ':/Markers/Images/Matplotlib_markers/' if face == 'none': #empty symbol marker_path = folder + 'marker_%s' % marker_name else: #filled symbol marker_path = folder + 'marker_filled_%s' % marker_name qp = QPixmap(marker_path) mask = qp.createMaskFromColor(QColor(0, 0, 0), Qt.MaskOutColor) qpainter = QPainter() qpainter.begin(qp) qpainter.setPen( QColor(int(255 * color[0]), int(255 * color[1]), int(255 * color[2]), 255)) qpainter.drawPixmap(qp.rect(), mask, qp.rect()) qpainter.end() item[0].setIcon(0, QIcon(qp)) self.DataSettreeWidget.blockSignals(False)
def _makePixmap(self, width, height): # setColor的子对象 函数调用 第一个问题就是大小 pixmap = QPixmap(width, height) #Pixmap似乎是专门搞这种笔刷显示工具的,为什么不让Painter进行大小设置?? style = self.brushComboBox.itemData(self.brushComboBox.currentIndex( )) # 获取次目数据,然后获取该index的Data数据(text,text data) brush = QBrush(self.color, Qt.BrushStyle(style)) #将花纹和颜色添加到笔刷上 painter = QPainter(pixmap) #画布内嵌地图 painter.fillRect(pixmap.rect(), Qt.white) # 底纹背景颜色,将其铺满画布 作为背景 其必须保持在前面而不是后面 painter.fillRect(pixmap.rect(), brush) # 将笔刷添加到Painter类的pixmap类型的画布中 return pixmap
def __init__(self, machine: Machine, *args, **kwargs): super().__init__(*args, **kwargs) self.machine = machine pm_play = QPixmap('imgs/play.png') pm_play_painter = QPainter(pm_play) pm_play_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) pm_play_painter.fillRect(pm_play.rect(), QColor(0, 192, 0)) pm_play_painter.end() pm_pause = QPixmap('imgs/pause.png') pm_pause_painter = QPainter(pm_pause) pm_pause_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) pm_pause_painter.fillRect(pm_pause.rect(), QColor(255, 64, 0)) pm_pause_painter.end() layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) w_name = QLabel(machine.name) w_name.setToolTip(machine.desc) layout.addWidget(w_name) self.layout_speed = MachineControlSpeedLayout(machine) layout.addWidget(self.layout_speed) pic_running = QLabel() pic_running.mousePressEvent = self.on_running if machine.running == RunningEnum.NOTRUNNING.value: pic_running.setPixmap(pm_pause) else: pic_running.setPixmap(pm_play) layout.addWidget(pic_running) # layout.addWidget(QLabel(machine.id)) # layout.addWidget(QLabel(machine.desc)) iname = QLabel(machine.iname) iname.setToolTip(machine.id) layout.addWidget(iname) pm_remove = QPixmap('imgs/close-thick.png') pm_remove_painter = QPainter(pm_remove) pm_remove_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) pm_remove_painter.fillRect(pm_remove.rect(), QColor(0, 102, 202)) pm_remove_painter.end() pic_remove = QLabel() pic_remove.mousePressEvent = self.on_remove pic_remove.setPixmap(pm_remove) layout.addWidget(pic_remove) self.setLayout(layout)
def main(): app = QApplication(sys.argv) import time start = time.time() splash_fname = utils.get_resource_path('icons/splash_ducks.jpg') splash_pix = QPixmap(splash_fname) size = splash_pix.size()*.55 splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) # below makes the pixmap half transparent painter = QPainter(splash_pix) painter.setCompositionMode(painter.CompositionMode_DestinationAtop) painter.fillRect(splash_pix.rect(), QColor(0, 0, 0, 100)) font = QFont() font.setFamily('Arial') font.setPointSize(40) font.setBold(True) painter.setFont(font) painter.setPen(QColor(250, 250, 250)) painter.drawText(splash_pix.rect(), Qt.AlignCenter, "Metadata Wizard") font = QFont() font.setFamily('Arial') font.setPointSize(19) font.setBold(True) painter.setFont(font) painter.setPen(QColor(150, 150, 150, 200)) painter.drawText(splash_pix.rect().adjusted(20, -20, -20, -20), Qt.AlignBottom, "version 0.0.0 pre-pre Alpha") painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.show() app.processEvents() time.sleep(2) app.processEvents() mdwiz = PyMdWizardMainForm() mdwiz.show() splash.finish(mdwiz) app.exec_()
def __grabRegion(self): """ Private method to grab the selected region (i.e. do the snapshot). """ pol = QPolygon(self.__selection) if not pol.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - pol.boundingRect().x() yOffset = self.__pixmap.rect().y() - pol.boundingRect().y() translatedPol = pol.translated(xOffset, yOffset) pixmap2 = QPixmap(pol.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawPolygon(translatedPol) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(QRegion(translatedPol)) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect()) pt.end() self.grabbed.emit(pixmap2)
def load_image(self, filename): """Load image to scene and create PIX """ self.image_name = filename self.scene.clear() self.zoomTo1() # Read image with leptonica => create PIX structure and report image # size info self.pix_image = self.leptonica.pixRead(self.image_name.encode()) self.image_width = self.leptonica.pixGetWidth(self.pix_image) self.image_height = self.leptonica.pixGetHeight(self.pix_image) self.show_msg("image size: %dx%d, resolution %dx%d" % (self.image_width, self.image_height, self.leptonica.pixGetXRes(self.pix_image), self.leptonica.pixGetYRes(self.pix_image) )) self.box_data = [] qimage = lept.pix_to_qimage(self.leptonica, self.pix_image) if not qimage: # fallback solution pixmap = QPixmap(filename) else: pixmap = QPixmap(qimage) self.image = self.scene.addPixmap(pixmap) self.scene.setSceneRect(QRectF(pixmap.rect())) self.setWindowTitle( 'Analyze & ORC image with tesseract and ' 'leptonica :: %s' % os.path.basename( self.image_name))
def create_pixmap( color: str = "#FFFFFF", frame_color: str = "#000000", size: int = 256, frame_size: int = 0, ) -> QPixmap: """Draw pixmap with frame and inner color. Args: color: Name of the inner color in hex format. frame_color: Name of the frame color in hex format. size: Total size of the pixmap in px. frame_size: Size of the frame to draw in px. """ # Initialize pixmap = QPixmap(size, size) painter = QPainter(pixmap) painter.setPen(Qt.NoPen) # Frame painter.setBrush(QColor(frame_color)) painter.drawRect(pixmap.rect()) # Inner painter.setBrush(QColor(color)) x = y = frame_size width = height = pixmap.width() - 2 * frame_size painter.drawRect(x, y, width, height) return pixmap
def paintEvent(self, event): painter = QPainter(self) pixmap = QPixmap(self.picPath) painter.drawPixmap(pixmap.rect(), pixmap) pen = QPen(Qt.red, 3) painter.setPen(pen) painter.drawRect(self.px, self.py, self.pw, self.ph)
class MyWindow(QWidget): def _init_(self): super(MyWindow, self)._init_() self.initGUI() def initGUI(self): self.setWindowTitle('A First Window') # A button self.mybutton = QPushButton(self) self.mybutton.setText("Ok!") # A text field self.mytext = QLineEdit(self) self.mytext.setText("Welcome") # An image filepath = "media/1.png" # relative path of your image file self.mypixmap = QPixmap(filepath) self.myimg = QLabel(self) self.myimg.setPixmap(self.mypixmap) # Set up the window and arrange all the widgets pixrect = self.mypixmap.rect() self.setGeometry(10, 10, pixrect.width(), pixrect.height() + 50) self.mytext.move(20, pixrect.height() + 20) self.mybutton.move(150, pixrect.height() + 15) self.show()
def mouseMoveEvent(self, e: QtGui.QMouseEvent) -> None: if e.buttons() != Qt.LeftButton: return None #根据currentIndex获取数据行的名称 mimeData = QMimeData() mimeData.setText('{}:{}:{}'.format(self.type, self.address, self.text())) #绘制拖动时的图像 pixmap = QPixmap(self.size()) paint = QPainter() paint.begin(pixmap) # paint.fillRect(pixmap.rect(),QColor(Qt.white)) # paint.drawRect(pixmap.rect()) paint.drawPixmap(self.rect(), self.grab()) paint.drawText(pixmap.rect(), Qt.AlignCenter, self.text()) paint.end() #设定拖动项的数据和图标 drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.exec_(Qt.MoveAction) super().mouseMoveEvent(e)
class PicScene(QGraphicsScene): originImageRect = 0 item = None imageLoaded = pyqtSignal() def __init__(self, parent): super().__init__(parent) gVar.imageViewImageSelectedEvent = self.ImageSelectedEvent def ImageSelectedEvent(self, path): self.AddImageCenter(path) self.update() self.imageLoaded.emit() def AddImageCenter(self, path): if self.item is not None: self.removeItem(self.item) self.image = QPixmap(path) sceneRect = self.sceneRect() self.originImageRect = self.image.rect() self.originImageRect.moveCenter(sceneRect.toRect().center()) self.item = QGraphicsPixmapItem(self.image) self.item.setOffset(self.originImageRect.x(), self.originImageRect.y()) self.addItem(self.item) def ResizeEvent(self, factor): pass
class Example(QMainWindow): def __init__(self): super().__init__() uic.loadUi('PIL20.ui', self) self.setGeometry(400, 400, 400, 400) self.setWindowTitle('Отображение картинки') self.fname = QFileDialog.getOpenFileName( self, 'Выбрать картинку', '', 'Картинка (*.jpg);;Картинка (*.jpg);;Все файлы (*)')[0] self.pixmap = QPixmap(self.fname) self.image = QLabel(self) self.image.move(140, 20) self.image.resize(220, 220) self.image.setPixmap(self.pixmap) self.pushButton.clicked.connect(self.change_color) self.pushButton_5.clicked.connect(self.change_def) self.pushButton_6.clicked.connect(self.change_def1) self.mask = self.pixmap.createMaskFromColor(QColor(255, 255, 255), Qt.MaskOutColor) def change_color(self): p = QPainter(self.pixmap) p.setPen(QColor(0, 0, 255)) p.drawPixmap(self.pixmap.rect(), self.mask, self.mask.rect()) p.end() def change_def(self): pass def change_def1(self): pass
def mousePressEvent(self, event): child = self.childAt(event.pos()) if not child: return pixmap = QPixmap(child.pixmap()) mimeData = QMimeData() mimeData.setText(child.type) drag = QDrag(self) drag.setPixmap(child.pixmap()) drag.setMimeData(mimeData) drag.setHotSpot(event.pos() - child.pos()) tempPixmap = QPixmap(pixmap) painter = QPainter() painter.begin(tempPixmap) painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127)) painter.end() child.setPixmap(tempPixmap) if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction: child.close() else: child.show() child.setPixmap(pixmap)
def mousePressEvent(self, event): child = self.childAt(event.pos()) if not child: return pixmap = QPixmap(child.pixmap()) itemData = QByteArray() dataStream = QDataStream(itemData, QIODevice.WriteOnly) dataStream << pixmap << QPoint(event.pos() - child.pos()) mimeData = QMimeData() mimeData.setData('application/x-dnditemdata', itemData) drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot(event.pos() - child.pos()) tempPixmap = QPixmap(pixmap) painter = QPainter() painter.begin(tempPixmap) painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127)) painter.end() child.setPixmap(tempPixmap) if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction: child.close() else: child.show() child.setPixmap(pixmap)
def png_asset(filename, set_to=None, size=32, color=(255, 255, 255), mask_color=( 0, 0, 0, ), **kw): fp = os.path.abspath(filename) if os.path.exists(fp): raise FileNotFoundError(fp) icon = QPixmap(fp) #icon.setStyleSheet("text-color: red") # scaled_icon = icon.scaled(30, 30, Qt.KeepAspectRatio & Qt.SmoothTransformation) mask = icon.createMaskFromColor(QColor(*mask_color), Qt.MaskOutColor) p = QPainter() p.begin(icon) p.setPen(QColor(*color)) p.drawPixmap(icon.rect(), mask, mask.rect()) p.end() scaled_icon = icon.scaledToHeight(size, Qt.SmoothTransformation) #scaled_icon.drawPixmap(pix.rect(), mask, mask.rect()) if set_to is not None: set_to.setPixmap(scaled_icon) return scaled_icon
def color_icon(self, color): color = self.qcolor(color) image = QPixmap(self.IMAGE_SIZE, self.IMAGE_SIZE) painter = QPainter(image) painter.fillRect(image.rect(), color) painter.end() return QIcon(image)
def crop2Area(self): """Perform crop action on Area item """ xb = int(self.area.pos().x()) yb = int(self.area.pos().y()) wb = int(self.area.rect().width()) hb = int(self.area.rect().height()) self.show_msg("Cropping area: {}, {}, {}, {}".format(xb, yb, wb, hb)) box = self.leptonica.boxCreate(xb, yb, wb, hb) cropped = self.leptonica.pixClipRectangle(self.pix_image, box, None) qimage = lept.pix_to_qimage(self.leptonica, cropped) pixmap = QPixmap(qimage) if pixmap: self.scene.removeItem(self.image) del self.image self.image = self.scene.addPixmap(pixmap) self.scene.setSceneRect(QRectF(pixmap.rect())) self.pix_image = cropped self.image_width = self.leptonica.pixGetWidth(self.pix_image) self.image_height = self.leptonica.pixGetHeight(self.pix_image) self.removeSceneItem() self.show_msg("New image size: %dx%d, resolution %dx%d" % (self.image_width, self.image_height, self.leptonica.pixGetXRes(self.pix_image), self.leptonica.pixGetYRes(self.pix_image) ))
def loadDataFromFile(self, filePath, which, point, tmpPoint = None, newPoint = None): pixmap = QPixmap(filePath) self.size = pixmap.size() painter = QPainter(pixmap) painter.drawPixmap(pixmap.rect(), pixmap) if point is not None: pen = QPen(QtCore.Qt.red, 5) painter.setPen(pen) painter.setBrush(QtCore.Qt.red) for n in point: painter.drawEllipse(QPointF(n[0], n[1]), 10, 10) if tmpPoint != None: painter.setPen(QPen(QtCore.Qt.green, 5)) painter.setBrush(QtCore.Qt.green) painter.drawEllipse(QPointF(tmpPoint[0], tmpPoint[1]), 10, 10) if point == self.leftPoint: self.tmpLDotPic = pixmap else: self.tmpRDotPic = pixmap if newPoint != None: painter.setPen(QPen(QtCore.Qt.blue, 5)) painter.setBrush(QtCore.Qt.blue) for n in newPoint: painter.drawEllipse(QPointF(n[0], n[1]), 10, 10) if point == self.leftPoint: self.leftDot = pixmap if point == self.rightPoint: self.rightDot = pixmap del painter which.setPixmap(pixmap) which.setScaledContents(True) if self.Left & self.Right: self.loadedState()
def _printLabel(self): # self.label.setText(self.__args[5]) if self.label.setObjectName=='Item_Name'else self.label.setText('') dialog = QPrintDialog(self.__printer, self) #choose printer if not dialog.exec_(): return for o in self.__oL: #set value to label # print(o.objectName()) if o.objectName() == 'ItemCode': o.setText(self.__args[1]) if o.objectName() == 'Barcode': o.setBarcode(self.__args[2]) if o.objectName() == 'ItemBarcode': o.setText(self.__args[2]) if o.objectName() == 'PLU': o.setText(self.__args[3]) if o.objectName() == 'ItemName': o.setText(self.__args[4]) # for s in self.__args: # print(s) painter = QPainter(self.__printer) image = QPixmap() image = self.grab( QRect(QPoint(0, 0), QSize(self.size().width(), self.size().height()))) # /* 绘制窗口至画布 */ rect = painter.viewport() size = image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(image.rect()) painter.drawPixmap(0, 0, image)
def paintEvent(self, event): """ Called when the widget is painted on the window. """ dpr = self.devicePixelRatioF() buffer = QPixmap(self.width() * dpr, self.height() * dpr) buffer.setDevicePixelRatio(dpr) buffer.fill(Qt.transparent) painter = QPainter(buffer) region = QRegion( QRect(0, 0, self._textWidget.sizeHint().width(), self._textWidget.sizeHint().height())) self._textWidget.render(painter, QPoint(0, 0), region) region = QRegion( QRect(0, 0, self._iconWidget.sizeHint().width(), self._iconWidget.sizeHint().height())) x = self._textWidget.sizeHint().width() + 3 self._iconWidget.render(painter, QPoint(x, 0), region) painter.end() painter = QPainter(self) painter.drawPixmap(event.rect(), buffer, buffer.rect()) painter.end()
def populatesThemesList(self): paths = allPaths("resources/themes") current = settings.fullScreenTheme self.lstThemes.clear() for p in paths: lst = [ i for i in os.listdir(p) if os.path.splitext(i)[1] == ".theme" ] for t in lst: theme = os.path.join(p, t) editable = not appPath() in theme n = getThemeName(theme) item = QListWidgetItem(n) item.setData(Qt.UserRole, theme) item.setData(Qt.UserRole + 1, editable) item.setToolTip("{}{}".format( n, self.tr(" (read-only)") if not editable else "")) thumb = os.path.join(p, t.replace(".theme", ".jpg")) px = QPixmap(200, 120) px.fill(Qt.white) if not os.path.exists(thumb): currentScreen = qApp.desktop().screenNumber(self) screenRect = qApp.desktop().screenGeometry(currentScreen) thumb = createThemePreview(theme, screenRect) icon = QPixmap(thumb).scaled(200, 120, Qt.KeepAspectRatio) painter = QPainter(px) painter.drawPixmap(px.rect().center() - icon.rect().center(), icon) painter.end() item.setIcon(QIcon(px)) self.lstThemes.addItem(item) if current and current in t: self.lstThemes.setCurrentItem(item) current = None self.lstThemes.setIconSize(QSize(200, 120)) if current: # the theme from settings wasn't found # select the last from the list self.lstThemes.setCurrentRow(self.lstThemes.count() - 1)
def _makePixmap(self, width, height): pixmap = QPixmap(width, height) style = self.brushComboBox.itemData(self.brushComboBox.currentIndex()) brush = QBrush(self.color, Qt.BrushStyle(style)) painter = QPainter(pixmap) painter.fillRect(pixmap.rect(), Qt.white) painter.fillRect(pixmap.rect(), brush) return pixmap
def _nextTetrominoPixmap(self): d = self.nextTetromino.dimensions pixmap = QPixmap(d * self.squareWidth(), d * self.squareHeight()) painter = QPainter(pixmap) painter.fillRect(pixmap.rect(), self.palette().window()) rect = pixmap.rect() cells = self.nextTetromino.cells for i in range(d): for j in range(d): if cells[i][j] != 0: self.drawSquare(painter, rect.left() + j * self.squareWidth(), rect.top() + i * self.squareHeight(), cells[i][j]) painter.end() return pixmap
def load_image(self, image: QPixmap): new_scene = SelectionScene(QRectF(image.rect()), parent=self) new_scene.addPixmap(image) editor_logger.info( f"Loaded scene: image-dimensions={image.rect().width(), image.rect().height()}" ) self._replace_scene(new_scene) new_scene.selection_drawing_finished.connect( self.on_selection_drawing_finished)
def setInfo(self, mnum, mname, mdesc, mlink, mrating): # Creates poster and title automatically poster = QtWidgets.QPushButton(self.scrollAreaWidgetContents) poster.setObjectName('poster%d' % mnum) posImage = QPixmap('images/%d.jpg' % mnum) poster.setIcon(QtGui.QIcon(posImage)) poster.setIconSize(posImage.rect().size()) poster.setFixedSize(posImage.rect().size()) if mnum == 0: posLength = 0 else: posLength = mnum * 185 posLength = 13 + posLength poster.setGeometry(QtCore.QRect(posLength, 10, 185, 281)) posName = mname poster.setToolTip(posName) poster.clicked.connect( lambda: self.movInfo(mnum, mname, mdesc, mlink, mrating))
def _makePixmap(self, width, height): pixmap = QPixmap(width, height) style = self.brushComboBox.itemData( self.brushComboBox.currentIndex()) brush = QBrush(self.color, Qt.BrushStyle(style)) painter = QPainter(pixmap) painter.fillRect(pixmap.rect(), Qt.white) painter.fillRect(pixmap.rect(), brush) return pixmap
def drawBackground(self, painter, rect): """ Reimplement QGraphicsView's drawBackground() method. """ scene_rect = self.scene.sceneRect() background = QPixmap("images/highway.jpg") bg_rectf = QRectF(background.rect()) painter.drawPixmap(scene_rect, background, bg_rectf)
def populatesThemesList(self): paths = allPaths("resources/themes") current = settings.fullScreenTheme self.lstThemes.clear() for p in paths: lst = [i for i in os.listdir(p) if os.path.splitext(i)[1] == ".theme"] for t in lst: theme = os.path.join(p, t) editable = not appPath() in theme n = getThemeName(theme) item = QListWidgetItem(n) item.setData(Qt.UserRole, theme) item.setData(Qt.UserRole + 1, editable) item.setToolTip("{}{}".format( n, self.tr(" (read-only)") if not editable else "")) thumb = os.path.join(p, t.replace(".theme", ".jpg")) px = QPixmap(200, 120) px.fill(Qt.white) if not os.path.exists(thumb): currentScreen = qApp.desktop().screenNumber(self) screenRect = qApp.desktop().screenGeometry(currentScreen) thumb = createThemePreview(theme, screenRect) icon = QPixmap(thumb).scaled(200, 120, Qt.KeepAspectRatio) painter = QPainter(px) painter.drawPixmap(px.rect().center() - icon.rect().center(), icon) painter.end() item.setIcon(QIcon(px)) self.lstThemes.addItem(item) if current and current in t: self.lstThemes.setCurrentItem(item) current = None self.lstThemes.setIconSize(QSize(200, 120)) if current: # the theme from settings wasn't found # select the last from the list self.lstThemes.setCurrentRow(self.lstThemes.count() - 1)
def drawMagnifierOnVideo(width, height, maskPixmap, dragPos, zoomPixmap, surface, painter, offset): ''' Draw Magnifier on Video ''' dim = min(width, height) MAX_MAGNIFIER = 229 magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) # reupdate our mask if maskPixmap.size() != box: maskPixmap = QPixmap(box) maskPixmap.fill(Qt.transparent) g = QRadialGradient() g.setCenter(radius, radius) g.setFocalPoint(radius, radius) g.setRadius(radius) g.setColorAt(1.0, QColor(64, 64, 64, 0)) g.setColorAt(0.5, QColor(0, 0, 0, 255)) mask = QPainter(maskPixmap) mask.setRenderHint(QPainter.HighQualityAntialiasing) mask.setCompositionMode(QPainter.CompositionMode_Source) mask.setBrush(g) mask.setPen(Qt.NoPen) mask.drawRect(maskPixmap.rect()) mask.setBrush(QColor(Qt.transparent)) mask.drawEllipse(g.center(), ring, ring) mask.end() center = dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * 2 - QPoint(radius, radius) # only set the dimension to the magnified portion if zoomPixmap.size() != box: zoomPixmap = QPixmap(box) zoomPixmap.fill(Qt.lightGray) if True: painter_p = QPainter(zoomPixmap) painter_p.translate(-xy) largePixmap = QPixmap.fromImage(surface.image) painter_p.drawPixmap(offset, largePixmap) painter_p.end() clipPath = QPainterPath() clipPath.addEllipse(QPointF(center), ring, ring) painter.setClipPath(clipPath) painter.drawPixmap(corner, zoomPixmap) painter.setClipping(False) painter.drawPixmap(corner, maskPixmap) painter.setPen(Qt.gray) painter.drawPath(clipPath) return
def drawTiles(painter, rect, tileSize=6, color=None, backgroundColor=None): sz = 2 * tileSize tiledPixmap = QPixmap(sz, sz) pixmapPainter = QPainter(tiledPixmap) pixmapPainter.setPen(Qt.NoPen) pixmapPainter.setBrush(Qt.Dense4Pattern) brush = pixmapPainter.brush() brush.setColor(color) pixmapPainter.setBrush(brush) pixmapPainter.setBackground(QBrush(backgroundColor)) pixmapPainter.setBackgroundMode(Qt.OpaqueMode) pixmapPainter.scale(tileSize, tileSize) pixmapPainter.drawRect(tiledPixmap.rect()) pixmapPainter.end() painter.drawTiledPixmap(rect, tiledPixmap)
def showNextPiece(self): if self.nextPieceLabel is not None: return dx = self.nextPiece.maxX() - self.nextPiece.minX() + 1 dy = self.nextPiece.maxY() - self.nextPiece.minY() + 1 pixmap = QPixmap(dx * self.squareWidth(), dy * self.squareHeight()) painter = QPainter(pixmap) painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().background()) for i in range(4): x = self.nextPiece.x(i) - self.nextPiece.minX() y = self.nextPiece.y(i) - self.nextPiece.minY() self.drawSquare(painter, x * self.squareWidth(), y * self.squareHeight(), self.nextPiece.shape()) self.nextPieceLabel.setPixmap(pixmap)
def load_icon(path): """Returns a QIcon with the image at path as the Normal state and the image recoloured as the Disabled state. """ pixmap = QPixmap(path) icon = QIcon() icon.addPixmap(pixmap) # Create disabled mask = pixmap.createMaskFromColor(QColor(0xff, 0xff, 0xff), Qt.MaskOutColor) p = QPainter(pixmap) p.setPen(QColor(0xaa, 0xaa, 0xaa)) p.drawPixmap(pixmap.rect(), mask, mask.rect()) p.end() icon.addPixmap(pixmap, QIcon.Disabled) return icon
def __grabRect(self): """ Private method to grab the selected rectangle (i.e. do the snapshot). """ if self.__mode == SnapshotRegionGrabber.Ellipse: ell = QRegion(self.__selection, QRegion.Ellipse) if not ell.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - ell.boundingRect().x() yOffset = self.__pixmap.rect().y() - ell.boundingRect().y() translatedEll = ell.translated(xOffset, yOffset) pixmap2 = QPixmap(ell.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawEllipse(translatedEll.boundingRect()) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(translatedEll) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, ell.boundingRect()) pt.end() self.grabbed.emit(pixmap2) else: r = QRect(self.__selection) if not r.isNull() and r.isValid(): self.__grabbing = True self.grabbed.emit(self.__pixmap.copy(r))
def draw_icon(icon, rect, painter, icon_mode, shadow=False): cache = icon.pixmap(rect.size()) dip_offset = QPoint(1, -2) cache = QPixmap() pixname = "icon {0} {1} {2}".format( icon.cacheKey(), icon_mode, rect.height() ) if QPixmapCache.find(pixname) is None: pix = icon.pixmap(rect.size()) device_pixel_ratio = pix.devicePixelRatio() radius = 3 * device_pixel_ratio offset = dip_offset * device_pixel_ratio cache = QPixmap(pix.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cache_painter = QPainter(cache) if icon_mode == QIcon.Disabled: im = pix.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(0, im.height()): scanline = im.scanLine(y) for x in range(0, im.width()): pixel = scanline intensity = qGray(pixel) scanline = qRgba( intensity, intensity, intensity, qAlpha(pixel)) scanline += 1 pix = QPixmap.fromImage(im) # Draw shadow tmp = QImage(pix.size() + QSize(radius * 2, radius * 2), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmp_painter = QPainter(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_Source) tmp_painter.drawPixmap( QRect(radius, radius, pix.width(), pix.height()), pix) tmp_painter.end() # Blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blur_painter = QPainter(blurred) blur_painter.end() # tmp = blurred tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() # Draw the blurred drop shadow cache_painter.drawImage( QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap cache_painter.drawPixmap( QRect(QPoint(radius, radius) + offset, QSize(pix.width(), pix.height())), pix) cache_painter.end() cache.setDevicePixelRatio(device_pixel_ratio) QPixmapCache.insert(pixname, cache) target_rect = cache.rect() target_rect.setSize(target_rect.size() / cache.devicePixelRatio()) target_rect.moveCenter(rect.center() - dip_offset) painter.drawPixmap(target_rect, cache)
class SnapshotRegionGrabber(QWidget): """ Class implementing a grabber widget for a rectangular snapshot region. @signal grabbed(QPixmap) emitted after the region was grabbed """ grabbed = pyqtSignal(QPixmap) StrokeMask = 0 FillMask = 1 Rectangle = 0 Ellipse = 1 def __init__(self, mode=Rectangle): """ Constructor @param mode region grabber mode (SnapshotRegionGrabber.Rectangle or SnapshotRegionGrabber.Ellipse) """ super(SnapshotRegionGrabber, self).__init__( None, Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool) assert mode in [SnapshotRegionGrabber.Rectangle, SnapshotRegionGrabber.Ellipse] self.__mode = mode self.__selection = QRect() self.__mouseDown = False self.__newSelection = False self.__handleSize = 10 self.__mouseOverHandle = None self.__showHelp = True self.__grabbing = False self.__dragStartPoint = QPoint() self.__selectionBeforeDrag = QRect() # naming conventions for handles # T top, B bottom, R Right, L left # 2 letters: a corner # 1 letter: the handle on the middle of the corresponding side self.__TLHandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__TRHandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__BLHandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__BRHandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__LHandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__THandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__RHandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__BHandle = QRect(0, 0, self.__handleSize, self.__handleSize) self.__handles = [self.__TLHandle, self.__TRHandle, self.__BLHandle, self.__BRHandle, self.__LHandle, self.__THandle, self.__RHandle, self.__BHandle] self.__helpTextRect = QRect() self.__helpText = self.tr( "Select a region using the mouse. To take the snapshot, press" " the Enter key or double click. Press Esc to quit.") self.__pixmap = QPixmap() self.setMouseTracking(True) QTimer.singleShot(200, self.__initialize) def __initialize(self): """ Private slot to initialize the rest of the widget. """ self.__desktop = QApplication.desktop() x = self.__desktop.x() y = self.__desktop.y() if qVersion() >= "5.0.0": self.__pixmap = QApplication.screens()[0].grabWindow( self.__desktop.winId(), x, y, self.__desktop.width(), self.__desktop.height()) else: self.__pixmap = QPixmap.grabWindow( self.__desktop.winId(), x, y, self.__desktop.width(), self.__desktop.height()) self.resize(self.__pixmap.size()) self.move(x, y) self.setCursor(Qt.CrossCursor) self.show() self.grabMouse() self.grabKeyboard() def paintEvent(self, evt): """ Protected method handling paint events. @param evt paint event (QPaintEvent) """ if self.__grabbing: # grabWindow() should just get the background return painter = QPainter(self) pal = QPalette(QToolTip.palette()) font = QToolTip.font() handleColor = pal.color(QPalette.Active, QPalette.Highlight) handleColor.setAlpha(160) overlayColor = QColor(0, 0, 0, 160) textColor = pal.color(QPalette.Active, QPalette.Text) textBackgroundColor = pal.color(QPalette.Active, QPalette.Base) painter.drawPixmap(0, 0, self.__pixmap) painter.setFont(font) r = QRect(self.__selection) if not self.__selection.isNull(): grey = QRegion(self.rect()) if self.__mode == SnapshotRegionGrabber.Ellipse: reg = QRegion(r, QRegion.Ellipse) else: reg = QRegion(r) grey = grey.subtracted(reg) painter.setClipRegion(grey) painter.setPen(Qt.NoPen) painter.setBrush(overlayColor) painter.drawRect(self.rect()) painter.setClipRect(self.rect()) drawRect(painter, r, handleColor) if self.__showHelp: painter.setPen(textColor) painter.setBrush(textBackgroundColor) self.__helpTextRect = painter.boundingRect( self.rect().adjusted(2, 2, -2, -2), Qt.TextWordWrap, self.__helpText).translated( -self.__desktop.x(), -self.__desktop.y()) self.__helpTextRect.adjust(-2, -2, 4, 2) drawRect(painter, self.__helpTextRect, textColor, textBackgroundColor) painter.drawText( self.__helpTextRect.adjusted(3, 3, -3, -3), Qt.TextWordWrap, self.__helpText) if self.__selection.isNull(): return # The grabbed region is everything which is covered by the drawn # rectangles (border included). This means that there is no 0px # selection, since a 0px wide rectangle will always be drawn as a line. txt = "{0:n}, {1:n} ({2:n} x {3:n})".format( self.__selection.x(), self.__selection.y(), self.__selection.width(), self.__selection.height()) textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt) boundingRect = textRect.adjusted(-4, 0, 0, 0) if textRect.width() < r.width() - 2 * self.__handleSize and \ textRect.height() < r.height() - 2 * self.__handleSize and \ r.width() > 100 and \ r.height() > 100: # center, unsuitable for small selections boundingRect.moveCenter(r.center()) textRect.moveCenter(r.center()) elif r.y() - 3 > textRect.height() and \ r.x() + textRect.width() < self.rect().width(): # on top, left aligned boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3)) textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3)) elif r.x() - 3 > textRect.width(): # left, top aligned boundingRect.moveTopRight(QPoint(r.x() - 3, r.y())) textRect.moveTopRight(QPoint(r.x() - 5, r.y())) elif r.bottom() + 3 + textRect.height() < self.rect().bottom() and \ r.right() > textRect.width(): # at bottom, right aligned boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3)) textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3)) elif r.right() + textRect.width() + 3 < self.rect().width(): # right, bottom aligned boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom())) textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom())) # If the above didn't catch it, you are running on a very # tiny screen... drawRect(painter, boundingRect, textColor, textBackgroundColor) painter.drawText(textRect, Qt.AlignHCenter, txt) if (r.height() > self.__handleSize * 2 and r.width() > self.__handleSize * 2) or \ not self.__mouseDown: self.__updateHandles() painter.setPen(Qt.NoPen) painter.setBrush(handleColor) painter.setClipRegion( self.__handleMask(SnapshotRegionGrabber.StrokeMask)) painter.drawRect(self.rect()) handleColor.setAlpha(60) painter.setBrush(handleColor) painter.setClipRegion( self.__handleMask(SnapshotRegionGrabber.FillMask)) painter.drawRect(self.rect()) def resizeEvent(self, evt): """ Protected method to handle resize events. @param evt resize event (QResizeEvent) """ if self.__selection.isNull(): return r = QRect(self.__selection) r.setTopLeft(self.__limitPointToRect(r.topLeft(), self.rect())) r.setBottomRight(self.__limitPointToRect(r.bottomRight(), self.rect())) if r.width() <= 1 or r.height() <= 1: # This just results in ugly drawing... self.__selection = QRect() else: self.__selection = self.__normalizeSelection(r) def mousePressEvent(self, evt): """ Protected method to handle mouse button presses. @param evt mouse press event (QMouseEvent) """ self.__showHelp = not self.__helpTextRect.contains(evt.pos()) if evt.button() == Qt.LeftButton: self.__mouseDown = True self.__dragStartPoint = evt.pos() self.__selectionBeforeDrag = QRect(self.__selection) if not self.__selection.contains(evt.pos()): self.__newSelection = True self.__selection = QRect() else: self.setCursor(Qt.ClosedHandCursor) elif evt.button() == Qt.RightButton: self.__newSelection = False self.__selection = QRect() self.setCursor(Qt.CrossCursor) self.update() def mouseMoveEvent(self, evt): """ Protected method to handle mouse movements. @param evt mouse move event (QMouseEvent) """ shouldShowHelp = not self.__helpTextRect.contains(evt.pos()) if shouldShowHelp != self.__showHelp: self.__showHelp = shouldShowHelp self.update() if self.__mouseDown: if self.__newSelection: p = evt.pos() r = self.rect() self.__selection = self.__normalizeSelection( QRect(self.__dragStartPoint, self.__limitPointToRect(p, r))) elif self.__mouseOverHandle is None: # moving the whole selection r = self.rect().normalized() s = self.__selectionBeforeDrag.normalized() p = s.topLeft() + evt.pos() - self.__dragStartPoint r.setBottomRight( r.bottomRight() - QPoint(s.width(), s.height()) + QPoint(1, 1)) if not r.isNull() and r.isValid(): self.__selection.moveTo(self.__limitPointToRect(p, r)) else: # dragging a handle r = QRect(self.__selectionBeforeDrag) offset = evt.pos() - self.__dragStartPoint if self.__mouseOverHandle in \ [self.__TLHandle, self.__THandle, self.__TRHandle]: r.setTop(r.top() + offset.y()) if self.__mouseOverHandle in \ [self.__TLHandle, self.__LHandle, self.__BLHandle]: r.setLeft(r.left() + offset.x()) if self.__mouseOverHandle in \ [self.__BLHandle, self.__BHandle, self.__BRHandle]: r.setBottom(r.bottom() + offset.y()) if self.__mouseOverHandle in \ [self.__TRHandle, self.__RHandle, self.__BRHandle]: r.setRight(r.right() + offset.x()) r.setTopLeft(self.__limitPointToRect(r.topLeft(), self.rect())) r.setBottomRight( self.__limitPointToRect(r.bottomRight(), self.rect())) self.__selection = self.__normalizeSelection(r) self.update() else: if self.__selection.isNull(): return found = False for r in self.__handles: if r.contains(evt.pos()): self.__mouseOverHandle = r found = True break if not found: self.__mouseOverHandle = None if self.__selection.contains(evt.pos()): self.setCursor(Qt.OpenHandCursor) else: self.setCursor(Qt.CrossCursor) else: if self.__mouseOverHandle in [self.__TLHandle, self.__BRHandle]: self.setCursor(Qt.SizeFDiagCursor) elif self.__mouseOverHandle in [self.__TRHandle, self.__BLHandle]: self.setCursor(Qt.SizeBDiagCursor) elif self.__mouseOverHandle in [self.__LHandle, self.__RHandle]: self.setCursor(Qt.SizeHorCursor) elif self.__mouseOverHandle in [self.__THandle, self.__BHandle]: self.setCursor(Qt.SizeVerCursor) def mouseReleaseEvent(self, evt): """ Protected method to handle mouse button releases. @param evt mouse release event (QMouseEvent) """ self.__mouseDown = False self.__newSelection = False if self.__mouseOverHandle is None and \ self.__selection.contains(evt.pos()): self.setCursor(Qt.OpenHandCursor) self.update() def mouseDoubleClickEvent(self, evt): """ Protected method to handle mouse double clicks. @param evt mouse double click event (QMouseEvent) """ self.__grabRect() def keyPressEvent(self, evt): """ Protected method to handle key presses. @param evt key press event (QKeyEvent) """ if evt.key() == Qt.Key_Escape: self.grabbed.emit(QPixmap()) elif evt.key() in [Qt.Key_Enter, Qt.Key_Return]: self.__grabRect() else: evt.ignore() def __updateHandles(self): """ Private method to update the handles. """ r = QRect(self.__selection) s2 = self.__handleSize // 2 self.__TLHandle.moveTopLeft(r.topLeft()) self.__TRHandle.moveTopRight(r.topRight()) self.__BLHandle.moveBottomLeft(r.bottomLeft()) self.__BRHandle.moveBottomRight(r.bottomRight()) self.__LHandle.moveTopLeft(QPoint(r.x(), r.y() + r.height() // 2 - s2)) self.__THandle.moveTopLeft(QPoint(r.x() + r.width() // 2 - s2, r.y())) self.__RHandle.moveTopRight( QPoint(r.right(), r.y() + r.height() // 2 - s2)) self.__BHandle.moveBottomLeft( QPoint(r.x() + r.width() // 2 - s2, r.bottom())) def __handleMask(self, maskType): """ Private method to calculate the handle mask. @param maskType type of the mask to be used (SnapshotRegionGrabber.FillMask or SnapshotRegionGrabber.StrokeMask) @return calculated mask (QRegion) """ mask = QRegion() for rect in self.__handles: if maskType == SnapshotRegionGrabber.StrokeMask: r = QRegion(rect) mask += r.subtracted(QRegion(rect.adjusted(1, 1, -1, -1))) else: mask += QRegion(rect.adjusted(1, 1, -1, -1)) return mask def __limitPointToRect(self, point, rect): """ Private method to limit the given point to the given rectangle. @param point point to be limited (QPoint) @param rect rectangle the point shall be limited to (QRect) @return limited point (QPoint) """ q = QPoint() if point.x() < rect.x(): q.setX(rect.x()) elif point.x() < rect.right(): q.setX(point.x()) else: q.setX(rect.right()) if point.y() < rect.y(): q.setY(rect.y()) elif point.y() < rect.bottom(): q.setY(point.y()) else: q.setY(rect.bottom()) return q def __normalizeSelection(self, sel): """ Private method to normalize the given selection. @param sel selection to be normalized (QRect) @return normalized selection (QRect) """ rect = QRect(sel) if rect.width() <= 0: left = rect.left() width = rect.width() rect.setLeft(left + width - 1) rect.setRight(left) if rect.height() <= 0: top = rect.top() height = rect.height() rect.setTop(top + height - 1) rect.setBottom(top) return rect def __grabRect(self): """ Private method to grab the selected rectangle (i.e. do the snapshot). """ if self.__mode == SnapshotRegionGrabber.Ellipse: ell = QRegion(self.__selection, QRegion.Ellipse) if not ell.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - ell.boundingRect().x() yOffset = self.__pixmap.rect().y() - ell.boundingRect().y() translatedEll = ell.translated(xOffset, yOffset) pixmap2 = QPixmap(ell.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawEllipse(translatedEll.boundingRect()) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(translatedEll) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, ell.boundingRect()) pt.end() self.grabbed.emit(pixmap2) else: r = QRect(self.__selection) if not r.isNull() and r.isValid(): self.__grabbing = True self.grabbed.emit(self.__pixmap.copy(r))
class MicRobotMain(QMainWindow): #For Kinect imgpos=0 depthList=[] imageList=[] KSAvailable=False #For robot #pl=R.listActivePorts() #R.setPar(pl[0],115200) #R.connect() def __init__(self): super(MicRobotMain, self).__init__() self.initUI() def initSim(self): self.simView=QWebView() self.angleInfo=AngleInfo() self.simView.page().mainFrame().\ addToJavaScriptWindowObject("angleInfo",self.angleInfo) self.simPath=QFileInfo("./html/index.html").absoluteFilePath() self.simView.setUrl(QUrl.fromLocalFile(self.simPath)) self.simView.setWindowFlags(Qt.FramelessWindowHint) def initRobot(self): self.Robot=MicRobot() ''' self.testLabel=QLabel() self.testLabel.setText("abc") self.testSlider=QSlider(Qt.Horizontal) self.testSlider.setRange(0,180) self.testSlider.setValue(0) self.testSlider.valueChanged.connect(self.fun) ''' def initKinectUI(self): #UI For Kinect RGB image and Depth image self.imgBlank=QImage("./image/kinect.png") self.depthLabel=QLabel() self.imageLabel=QLabel() self.depthLabel.setAlignment(Qt.AlignCenter) self.imageLabel.setAlignment(Qt.AlignCenter) self.depthList.append(self.imgBlank) self.depthList.append(self.imgBlank) self.imageList.append(self.imgBlank) self.imageList.append(self.imgBlank) self.depthLabel.setPixmap(QPixmap.fromImage(self.imgBlank).scaled( self.depthLabel.width(), self.depthLabel.height(), Qt.KeepAspectRatio)) self.imageLabel.setPixmap(QPixmap.fromImage(self.imgBlank).scaled( self.depthLabel.width(), self.depthLabel.height(), Qt.KeepAspectRatio)) def initCommLayerUI(self): self.imgKinectAvailable=QImage("./image/kinect_available.png") self.imgKinectDisable=QImage("./image/kinect_disable.png") self.imgRobotAvailable=QImage("./image/robot_available.png") self.imgRobotDisable=QImage("./image/robot_disable.png") self.imgMain=QImage("./image/microbot_long.png") self.commKinectLabel=QLabel() self.commMainLabel=QLabel() self.commRobotLabel=QLabel() self.commKinectLabel.setPixmap(QPixmap.fromImage(self.imgKinectAvailable)) self.commMainLabel.setPixmap(QPixmap.fromImage(self.imgMain)) self.commRobotLabel.setPixmap(QPixmap.fromImage(self.imgRobotDisable)) #K Kinect #M Main #R Robot #self.commKMLabel=QLabel() #self.commMRLabel=QLabel() #self.imgConnected=QImage("./image/connected.png") #self.imgDisconnected=QImage("./image/disconnected.png") #self.commKMLabel.setPixmap(QPixmap.fromImage(self.imgDisconnected)) #self.commMRLabel.setPixmap(QPixmap.fromImage(self.imgDisconnected)) self.pmConnected=QPixmap("./image/connected.png") self.pmDisconnected=QPixmap("./image/disconnected.png") self.iconConnected=QIcon(self.pmConnected) self.iconDisconnected=QIcon(self.pmDisconnected) self.commKMButton=QPushButton() self.commMRButton=QPushButton() self.commKMButton.setIcon(self.iconDisconnected) self.commMRButton.setIcon(self.iconDisconnected) self.commKMButton.setIconSize(self.pmDisconnected.rect().size()) self.commMRButton.setIconSize(self.pmDisconnected.rect().size()) self.commKMButton.setDisabled(True) self.commMRButton.setDisabled(True) self.commLayerLayout=QHBoxLayout() self.commLayerLayout.addWidget(self.commKinectLabel) #self.commLayerLayout.addWidget(self.commKMLabel) self.commLayerLayout.addWidget(self.commKMButton) self.commLayerLayout.addWidget(self.commMainLabel) #self.commLayerLayout.addWidget(self.commMRLabel) self.commLayerLayout.addWidget(self.commMRButton) self.commLayerLayout.addWidget(self.commRobotLabel) self.commLayerLayout.setAlignment(Qt.AlignCenter) self.commLayerWidget=QWidget() self.commLayerWidget.setLayout(self.commLayerLayout) self.MRConnected=False self.KMConnected=False self.commMRButton.clicked.connect(self.MRButtonClick) self.commKMButton.clicked.connect(self.KMButtonClick) def disconnectKM(self): self.KMConnected=False self.angleInfo.KMConnectedV=False self.commKMButton.setIcon(self.iconDisconnected) def connectKM(self): self.KMConnected=True self.angleInfo.KMConnectedV=True self.commKMButton.setIcon(self.iconConnected) def disconnectMR(self): self.MRConnected=False self.commMRButton.setIcon(self.iconDisconnected) def connectMR(self): self.MRConnected=True self.commMRButton.setIcon(self.iconConnected) def KMButtonClick(self): if self.KMConnected: self.disconnectKM() else: self.connectKM() def MRButtonClick(self): if self.MRConnected: self.disconnectMR() else: self.connectMR() def initRefreshTimer(self): self.refreshThread=RefreshTimerThread() self.kstimer=QTimer() self.refreshThread.setup(self) self.refreshThread.start() self.kstimer.start(1000) def initKSCheckTimer(self): self.kschecktimer=QTimer() self.kschecktimer.timeout.connect( partial(self.KSCheck,trigger='timercheck')) self.kschecktimer.start(40) def initRobotTimer(self): self.robotTimer=QTimer() self.robotTimer.timeout.connect(self.Robot.checkAvailable) self.robotTimer.start(1000) self.refreshRobotThread=RefreshRobotThread(self) self.robottimer=QTimer() self.refreshRobotThread.start() def initUI(self): self.initSim() self.initRobot() self.initKinectUI() self.initCommLayerUI() #Construcet Left UI self.leftLayout=QVBoxLayout() self.leftLayout.addWidget(self.commLayerWidget) self.leftLayout.addWidget(self.imageLabel) self.leftLayout.addWidget(self.depthLabel) self.leftSide=QWidget() self.leftSide.setLayout(self.leftLayout) self.leftSide.setWindowFlags(Qt.FramelessWindowHint) #Construct splitter self.split=QSplitter(Qt.Horizontal) self.split.addWidget(self.leftSide) self.split.addWidget(self.simView) #Init timers self.initRefreshTimer() self.connectComm() self.initKSCheckTimer() self.initRobotTimer() #show self.split.show() #self.split.showFullScreen() self.commKinectLabel.setScaledContents(True) def kinectReady(self): self.commKinectLabel.setPixmap(QPixmap.fromImage(self.imgKinectAvailable)) self.commKMButton.setEnabled(True) def kinectFail(self): self.commKinectLabel.setPixmap(QPixmap.fromImage(self.imgKinectDisable)) self.disconnectKM() self.commKMButton.setDisabled(True) def robotReady(self): self.commRobotLabel.setPixmap(QPixmap.fromImage(self.imgRobotAvailable)) self.commMRButton.setEnabled(True) def robotFail(self): self.commRobotLabel.setPixmap(QPixmap.fromImage(self.imgRobotDisable)) self.disconnectMR() self.commMRButton.setDisabled(True) def connectComm(self): self.refreshThread.KinectReady.connect(self.kinectReady) self.refreshThread.KinectFail.connect(self.kinectFail) self.Robot.serReady.connect(self.robotReady) self.Robot.serFail.connect(self.robotFail) #Check kinect availability def KSCheck(self,trigger): if trigger=='timercheck': if self.KSAvailable!=True and KS.deviceAvailable(): ####Here may also fail KS.startAll() self.KSAvailable=True self.refreshThread.KinectReady.emit() elif trigger=='failurecheck': print "failurecheck" KS.reInit() if not KS.deviceAvailable(): print "failurecheck failed" self.KSAvailable=False self.refreshThread.KinectFail.emit()
def tray(self): temp_decimal = eval(self.settings.value('Decimal') or 'False') try: if temp_decimal: temp_tray = self.temp_decimal else: temp_tray = self.temp except: # First time launch return if self.inerror or not hasattr(self, 'temp'): logging.critical('Cannot paint icon!') if hasattr(self, 'overviewcity'): try: # delete dialog to prevent memory leak self.overviewcity.close() except: pass return try: self.gif_loading.stop() except: # In first time run the gif is not animated pass logging.debug('Paint tray icon...') # Place empty.png here to initialize the icon # don't paint the T° over the old value icon = QPixmap(':/empty') self.traycolor = self.settings.value('TrayColor') or '' self.fontsize = self.settings.value('FontSize') or '18' self.tray_type = self.settings.value('TrayType') or 'icon&temp' pt = QPainter() pt.begin(icon) if self.tray_type != 'temp': pt.drawPixmap(0, -12, 64, 64, self.wIcon) pt.setFont(QFont('sans-sertif', int(self.fontsize))) pt.setPen(QColor(self.traycolor)) if self.tray_type == 'icon&temp': pt.drawText(icon.rect(), Qt.AlignBottom | Qt.AlignCenter, str(temp_tray)) if self.tray_type == 'temp': pt.drawText(icon.rect(), Qt.AlignCenter, str(temp_tray)) pt.end() if self.tray_type == 'icon': self.systray.setIcon(QIcon(self.wIcon)) else: self.systray.setIcon(QIcon(icon)) try: if not self.overviewcity.isVisible(): notifier = self.settings.value('Notifications') or 'True' notifier = eval(notifier) if notifier: temp = int(re.search('\d+', self.temp_decimal).group()) if temp != self.notification_temp or self.id_ != self.notifications_id: self.notifications_id = self.id_ self.notification_temp = temp self.systray.showMessage('meteo-qt', self.notification) except: logging.debug('OverviewCity has been deleted' + 'Download weather information again...') self.try_again() return self.restore_city() self.tentatives = 0 self.tooltip_weather() logging.info('Actual weather status for: ' + self.notification)
class TetrixBoard(QFrame): BoardWidth = 11 BoardHeight = 22 scoreChanged = pyqtSignal(int) levelChanged = pyqtSignal(int) linesRemovedChanged = pyqtSignal(int) act = pyqtSignal(int, "PyQt_PyObject") def __init__(self, parent = None): super(TetrixBoard, self).__init__(parent) self.setStyleSheet("background-color:black;border:2px solid darkGreen;") self.timer = QBasicTimer() self.nextPieceLabel = None self.isWaitingAfterLine = False self.curPiece = TetrixPiece() self.nextPiece = TetrixPiece() self.curX = 0 self.curY = 0 self.numLinesRemoved = 0 self.numPiecesDropped = 0 self.score = 0 self.level = 0 self.board = None #self.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.setFrameStyle(QFrame.Box) self.setFocusPolicy(Qt.StrongFocus) self.isStarted = False self.isPaused = False self.clearBoard() self.nextPiece.setRandomShape() def focusOutEvent(self, event): if self.isStarted and not self.isPaused: self.pause() QFrame.focusOutEvent(self, event) def shapeAt(self, x, y): return self.board[(y * TetrixBoard.BoardWidth) + x] def setShapeAt(self, x, y, shape): self.board[(y * TetrixBoard.BoardWidth) + x] = shape def timeoutTime(self): return 1000 // (1 + self.level) def squareWidth(self): return self.contentsRect().width() // TetrixBoard.BoardWidth def squareHeight(self): return self.contentsRect().height() // TetrixBoard.BoardHeight def setNextPieceLabel(self, label): self.nextPieceLabel = label #label.setScaledContents(True) label.setMinimumSize(label.width(), label.width()) def sizeHint(self): return QSize(TetrixBoard.BoardWidth * 15 + self.frameWidth() * 2, TetrixBoard.BoardHeight * 15 + self.frameWidth() * 2) def minimumSizeHint(self): return QSize(TetrixBoard.BoardWidth * 15 + self.frameWidth() * 2, TetrixBoard.BoardHeight * 15 + self.frameWidth() * 2) def start(self): if self.isPaused: return self.isStarted = True self.isWaitingAfterLine = False self.numLinesRemoved = 0 self.numPiecesDropped = 0 self.score = 0 self.level = 1 self.clearBoard() self.linesRemovedChanged.emit(self.numLinesRemoved) self.scoreChanged.emit(self.score) self.levelChanged.emit(self.level) self.newPiece() self.timer.start(self.timeoutTime(), self) def pause(self): if not self.isStarted: return self.isPaused = not self.isPaused if self.isPaused: self.timer.stop() else: self.timer.start(self.timeoutTime(), self) self.update() def paintEvent(self, event): super(TetrixBoard, self).paintEvent(event) painter = QPainter(self) rect = self.contentsRect() if self.isPaused: painter.drawText(rect, Qt.AlignCenter, self.tr("Pause")) return boardTop = rect.bottom() - TetrixBoard.BoardHeight * self.squareHeight() for i in range(TetrixBoard.BoardHeight): for j in range(TetrixBoard.BoardWidth): shape = self.shapeAt(j, TetrixBoard.BoardHeight - i - 1) if shape != NoShape: self.drawSquare(painter, rect.left() + j * self.squareWidth(), boardTop + i * self.squareHeight(), shape) if self.curPiece.shape() != NoShape: for i in range(4): x = self.curX + self.curPiece.x(i) y = self.curY - self.curPiece.y(i) self.drawSquare(painter, rect.left() + x * self.squareWidth(), boardTop + (TetrixBoard.BoardHeight - y - 1) * self.squareHeight(), self.curPiece.shape()) def keyPressEvent(self, event): if not self.isStarted or self.isPaused or self.curPiece.shape() == NoShape: super(TetrixBoard, self).keyPressEvent(event) return key = event.key() if key == Qt.Key_Left: self.tryMove(self.curPiece, self.curX - 1, self.curY) elif key == Qt.Key_Right: self.tryMove(self.curPiece, self.curX + 1, self.curY) elif key == Qt.Key_Down: self.tryMove(self.curPiece.rotatedRight(), self.curX, self.curY) elif key == Qt.Key_Up: self.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY) elif key == Qt.Key_Space: self.dropDown() elif key == Qt.Key_D: self.oneLineDown() else: super(TetrixBoard, self).keyPressEvent(event) def timerEvent(self, event): if event.timerId() == self.timer.timerId(): if self.isWaitingAfterLine: self.isWaitingAfterLine = False self.newPiece() self.timer.start(self.timeoutTime(), self) else: self.oneLineDown() else: super(TetrixBoard, self).timerEvent(event) def clearBoard(self): self.board = [NoShape for i in range(TetrixBoard.BoardHeight * TetrixBoard.BoardWidth)] def dropDown(self): dropHeight = 0 newY = self.curY while newY > 0: if not self.tryMove(self.curPiece, self.curX, newY - 1): break newY -= 1 dropHeight += 1 self.pieceDropped(dropHeight) def oneLineDown(self): if not self.tryMove(self.curPiece, self.curX, self.curY - 1): self.pieceDropped(0) def pieceDropped(self, dropHeight): for i in range(4): x = self.curX + self.curPiece.x(i) y = self.curY - self.curPiece.y(i) self.setShapeAt(x, y, self.curPiece.shape()) self.numPiecesDropped += 1 if self.numPiecesDropped % 25 == 0: self.level += 1 self.timer.start(self.timeoutTime(), self) self.levelChanged.emit(self.level) self.score += dropHeight + 7 self.scoreChanged.emit(self.score) self.removeFullLines() if not self.isWaitingAfterLine: self.newPiece() def removeFullLines(self): numFullLines = 0 for i in range(TetrixBoard.BoardHeight - 1, -1, -1): lineIsFull = True for j in range(TetrixBoard.BoardWidth): if self.shapeAt(j, i) == NoShape: lineIsFull = False break if lineIsFull: numFullLines += 1 for k in range(i, TetrixBoard.BoardHeight - 1): for j in range(TetrixBoard.BoardWidth): self.setShapeAt(j, k, self.shapeAt(j, k + 1)) for j in range(TetrixBoard.BoardWidth): self.setShapeAt(j, TetrixBoard.BoardHeight - 1, NoShape) if numFullLines > 0: self.numLinesRemoved += numFullLines self.score += 10 * numFullLines self.linesRemovedChanged.emit(self.numLinesRemoved) self.scoreChanged.emit(self.score) self.timer.start(200, self) self.isWaitingAfterLine = True self.curPiece.setShape(NoShape) self.update() def newPiece(self): self.curPiece = self.nextPiece self.nextPiece = TetrixPiece() self.nextPiece.setRandomShape() self.showNextPiece() self.curX = TetrixBoard.BoardWidth // 2 self.curY = TetrixBoard.BoardHeight - 1 + self.curPiece.minY() self.act.emit(self.curX, self.curPiece) if not self.tryMove(self.curPiece, self.curX, self.curY): self.curPiece.setShape(NoShape) self.timer.stop() self.isStarted = False def showNextPiece(self): if self.nextPieceLabel is None: return dx = self.nextPiece.maxX() - self.nextPiece.minX() + 1 dy = self.nextPiece.maxY() - self.nextPiece.minY() + 1 self.pixmapNextPiece = QPixmap(dx * self.squareWidth(), dy * self.squareHeight()) painter = QPainter(self.pixmapNextPiece) painter.fillRect(self.pixmapNextPiece.rect(), self.nextPieceLabel.palette().brush(QPalette.Background)) for i in range(4): x = self.nextPiece.x(i) - self.nextPiece.minX() y = self.nextPiece.y(i) - self.nextPiece.minY() self.drawSquare(painter, x * self.squareWidth(), y * self.squareHeight(), self.nextPiece.shape()) self.nextPieceLabel.setPixmap(self.pixmapNextPiece) def tryMove(self, newPiece, newX, newY): for i in range(4): x = newX + newPiece.x(i) y = newY - newPiece.y(i) if x < 0 or x >= TetrixBoard.BoardWidth or y < 0 or y >= TetrixBoard.BoardHeight: return False if self.shapeAt(x, y) != NoShape: return False self.curPiece = newPiece self.curX = newX self.curY = newY self.update() self.act.emit(self.curX, self.curPiece) return True def drawSquare(self, painter, x, y, shape): colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00] color = QColor(colorTable[shape]) painter.fillRect(x + 1, y + 1, self.squareWidth() - 2, self.squareHeight() - 2, color) painter.setPen(color.lighter()) painter.drawLine(x, y + self.squareHeight() - 1, x, y) painter.drawLine(x, y, x + self.squareWidth() - 1, y) painter.setPen(color.darker()) painter.drawLine(x + 1, y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + self.squareHeight() - 1) painter.drawLine(x + self.squareWidth() - 1, y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)
class SnapshotFreehandGrabber(QWidget): """ Class implementing a grabber widget for a freehand snapshot region. @signal grabbed(QPixmap) emitted after the region was grabbed """ grabbed = pyqtSignal(QPixmap) def __init__(self): """ Constructor """ super(SnapshotFreehandGrabber, self).__init__( None, Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool) self.__selection = QPolygon() self.__mouseDown = False self.__newSelection = False self.__handleSize = 10 self.__showHelp = True self.__grabbing = False self.__dragStartPoint = QPoint() self.__selectionBeforeDrag = QPolygon() self.__locale = QLocale() self.__helpTextRect = QRect() self.__helpText = self.tr( "Select a region using the mouse. To take the snapshot," " press the Enter key or double click. Press Esc to quit.") self.__pixmap = QPixmap() self.__pBefore = QPoint() self.setMouseTracking(True) QTimer.singleShot(200, self.__initialize) def __initialize(self): """ Private slot to initialize the rest of the widget. """ self.__desktop = QApplication.desktop() x = self.__desktop.x() y = self.__desktop.y() if qVersion() >= "5.0.0": self.__pixmap = QApplication.screens()[0].grabWindow( self.__desktop.winId(), x, y, self.__desktop.width(), self.__desktop.height()) else: self.__pixmap = QPixmap.grabWindow( self.__desktop.winId(), x, y, self.__desktop.width(), self.__desktop.height()) self.resize(self.__pixmap.size()) self.move(x, y) self.setCursor(Qt.CrossCursor) self.show() self.grabMouse() self.grabKeyboard() self.activateWindow() def paintEvent(self, evt): """ Protected method handling paint events. @param evt paint event (QPaintEvent) """ if self.__grabbing: # grabWindow() should just get the background return painter = QPainter(self) pal = QPalette(QToolTip.palette()) font = QToolTip.font() handleColor = pal.color(QPalette.Active, QPalette.Highlight) handleColor.setAlpha(160) overlayColor = QColor(0, 0, 0, 160) textColor = pal.color(QPalette.Active, QPalette.Text) textBackgroundColor = pal.color(QPalette.Active, QPalette.Base) painter.drawPixmap(0, 0, self.__pixmap) painter.setFont(font) pol = QPolygon(self.__selection) if not self.__selection.boundingRect().isNull(): # Draw outline around selection. # Important: the 1px-wide outline is *also* part of the # captured free-region pen = QPen(handleColor, 1, Qt.SolidLine, Qt.SquareCap, Qt.BevelJoin) painter.setPen(pen) painter.drawPolygon(pol) # Draw the grey area around the selection. grey = QRegion(self.rect()) grey = grey - QRegion(pol) painter.setClipRegion(grey) painter.setPen(Qt.NoPen) painter.setBrush(overlayColor) painter.drawRect(self.rect()) painter.setClipRect(self.rect()) drawPolygon(painter, pol, handleColor) if self.__showHelp: painter.setPen(textColor) painter.setBrush(textBackgroundColor) self.__helpTextRect = painter.boundingRect( self.rect().adjusted(2, 2, -2, -2), Qt.TextWordWrap, self.__helpText).translated( -self.__desktop.x(), -self.__desktop.y()) self.__helpTextRect.adjust(-2, -2, 4, 2) drawPolygon(painter, self.__helpTextRect, textColor, textBackgroundColor) painter.drawText( self.__helpTextRect.adjusted(3, 3, -3, -3), Qt.TextWordWrap, self.__helpText) if self.__selection.isEmpty(): return # The grabbed region is everything which is covered by the drawn # rectangles (border included). This means that there is no 0px # selection, since a 0px wide rectangle will always be drawn as a line. boundingRect = self.__selection.boundingRect() txt = "{0}, {1} ({2} x {3})".format( self.__locale.toString(boundingRect.x()), self.__locale.toString(boundingRect.y()), self.__locale.toString(boundingRect.width()), self.__locale.toString(boundingRect.height()) ) textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt) boundingRect = textRect.adjusted(-4, 0, 0, 0) polBoundingRect = pol.boundingRect() if (textRect.width() < polBoundingRect.width() - 2 * self.__handleSize) and \ (textRect.height() < polBoundingRect.height() - 2 * self.__handleSize) and \ polBoundingRect.width() > 100 and \ polBoundingRect.height() > 100: # center, unsuitable for small selections boundingRect.moveCenter(polBoundingRect.center()) textRect.moveCenter(polBoundingRect.center()) elif polBoundingRect.y() - 3 > textRect.height() and \ polBoundingRect.x() + textRect.width() < self.rect().width(): # on top, left aligned boundingRect.moveBottomLeft( QPoint(polBoundingRect.x(), polBoundingRect.y() - 3)) textRect.moveBottomLeft( QPoint(polBoundingRect.x() + 2, polBoundingRect.y() - 3)) elif polBoundingRect.x() - 3 > textRect.width(): # left, top aligned boundingRect.moveTopRight( QPoint(polBoundingRect.x() - 3, polBoundingRect.y())) textRect.moveTopRight( QPoint(polBoundingRect.x() - 5, polBoundingRect.y())) elif (polBoundingRect.bottom() + 3 + textRect.height() < self.rect().bottom()) and \ polBoundingRect.right() > textRect.width(): # at bottom, right aligned boundingRect.moveTopRight( QPoint(polBoundingRect.right(), polBoundingRect.bottom() + 3)) textRect.moveTopRight( QPoint(polBoundingRect.right() - 2, polBoundingRect.bottom() + 3)) elif polBoundingRect.right() + textRect.width() + 3 < \ self.rect().width(): # right, bottom aligned boundingRect.moveBottomLeft( QPoint(polBoundingRect.right() + 3, polBoundingRect.bottom())) textRect.moveBottomLeft( QPoint(polBoundingRect.right() + 5, polBoundingRect.bottom())) # If the above didn't catch it, you are running on a very # tiny screen... drawPolygon(painter, boundingRect, textColor, textBackgroundColor) painter.drawText(textRect, Qt.AlignHCenter, txt) if (polBoundingRect.height() > self.__handleSize * 2 and polBoundingRect.width() > self.__handleSize * 2) or \ not self.__mouseDown: painter.setBrush(Qt.transparent) painter.setClipRegion(QRegion(pol)) painter.drawPolygon(QPolygon(self.rect())) def mousePressEvent(self, evt): """ Protected method to handle mouse button presses. @param evt mouse press event (QMouseEvent) """ self.__pBefore = evt.pos() self.__showHelp = not self.__helpTextRect.contains(evt.pos()) if evt.button() == Qt.LeftButton: self.__mouseDown = True self.__dragStartPoint = evt.pos() self.__selectionBeforeDrag = QPolygon(self.__selection) if not self.__selection.containsPoint(evt.pos(), Qt.WindingFill): self.__newSelection = True self.__selection = QPolygon() else: self.setCursor(Qt.ClosedHandCursor) elif evt.button() == Qt.RightButton: self.__newSelection = False self.__selection = QPolygon() self.setCursor(Qt.CrossCursor) self.update() def mouseMoveEvent(self, evt): """ Protected method to handle mouse movements. @param evt mouse move event (QMouseEvent) """ shouldShowHelp = not self.__helpTextRect.contains(evt.pos()) if shouldShowHelp != self.__showHelp: self.__showHelp = shouldShowHelp self.update() if self.__mouseDown: if self.__newSelection: p = evt.pos() self.__selection.append(p) else: # moving the whole selection p = evt.pos() - self.__pBefore # Offset self.__pBefore = evt.pos() # save position for next iteration self.__selection.translate(p) self.update() else: if self.__selection.boundingRect().isEmpty(): return if self.__selection.containsPoint(evt.pos(), Qt.WindingFill): self.setCursor(Qt.OpenHandCursor) else: self.setCursor(Qt.CrossCursor) def mouseReleaseEvent(self, evt): """ Protected method to handle mouse button releases. @param evt mouse release event (QMouseEvent) """ self.__mouseDown = False self.__newSelection = False if self.__selection.containsPoint(evt.pos(), Qt.WindingFill): self.setCursor(Qt.OpenHandCursor) self.update() def mouseDoubleClickEvent(self, evt): """ Protected method to handle mouse double clicks. @param evt mouse double click event (QMouseEvent) """ self.__grabRegion() def keyPressEvent(self, evt): """ Protected method to handle key presses. @param evt key press event (QKeyEvent) """ if evt.key() == Qt.Key_Escape: self.grabbed.emit(QPixmap()) elif evt.key() in [Qt.Key_Enter, Qt.Key_Return]: self.__grabRegion() else: evt.ignore() def __grabRegion(self): """ Private method to grab the selected region (i.e. do the snapshot). """ pol = QPolygon(self.__selection) if not pol.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - pol.boundingRect().x() yOffset = self.__pixmap.rect().y() - pol.boundingRect().y() translatedPol = pol.translated(xOffset, yOffset) pixmap2 = QPixmap(pol.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawPolygon(translatedPol) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(QRegion(translatedPol)) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect()) pt.end() self.grabbed.emit(pixmap2)
class LightMaps(QWidget): def __init__(self, parent = None): super(LightMaps, self).__init__(parent) self.pressed = False self.snapped = False self.zoomed = False self.invert = False self._normalMap = SlippyMap(self) self._largeMap = SlippyMap(self) self.pressPos = QPoint() self.dragPos = QPoint() self.tapTimer = QBasicTimer() self.zoomPixmap = QPixmap() self.maskPixmap = QPixmap() self._normalMap.updated.connect(self.updateMap) self._largeMap.updated.connect(self.update) def setCenter(self, lat, lng): self._normalMap.latitude = lat self._normalMap.longitude = lng self._normalMap.invalidate() self._largeMap.invalidate() # slots def toggleNightMode(self): self.invert = not self.invert self.update() def updateMap(self, r): self.update(r) def activateZoom(self): self.zoomed = True self.tapTimer.stop() self._largeMap.zoom = self._normalMap.zoom + 1 self._largeMap.width = self._normalMap.width * 2 self._largeMap.height = self._normalMap.height * 2 self._largeMap.latitude = self._normalMap.latitude self._largeMap.longitude = self._normalMap.longitude self._largeMap.invalidate() self.update() def resizeEvent(self, event): self._normalMap.width = self.width() self._normalMap.height = self.height() self._normalMap.invalidate() self._largeMap.width = self._normalMap.width * 2 self._largeMap.height = self._normalMap.height * 2 self._largeMap.invalidate() def paintEvent(self, event): p = QPainter() p.begin(self) self._normalMap.render(p, event.rect()) p.setPen(Qt.black) p.drawText(self.rect(), Qt.AlignBottom | Qt.TextWordWrap, "Map data CCBYSA 2009 OpenStreetMap.org contributors") p.end() if self.zoomed: dim = min(self.width(), self.height()) magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) # reupdate our mask if self.maskPixmap.size() != box: self.maskPixmap = QPixmap(box) self.maskPixmap.fill(Qt.transparent) g = QRadialGradient() g.setCenter(radius, radius) g.setFocalPoint(radius, radius) g.setRadius(radius) g.setColorAt(1.0, QColor(255, 255, 255, 0)) g.setColorAt(0.5, QColor(128, 128, 128, 255)) mask = QPainter(self.maskPixmap) mask.setRenderHint(QPainter.Antialiasing) mask.setCompositionMode(QPainter.CompositionMode_Source) mask.setBrush(g) mask.setPen(Qt.NoPen) mask.drawRect(self.maskPixmap.rect()) mask.setBrush(QColor(Qt.transparent)) mask.drawEllipse(g.center(), ring, ring) mask.end() center = self.dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * 2 - QPoint(radius, radius) # only set the dimension to the magnified portion if self.zoomPixmap.size() != box: self.zoomPixmap = QPixmap(box) self.zoomPixmap.fill(Qt.lightGray) if True: p = QPainter(self.zoomPixmap) p.translate(-xy) self._largeMap.render(p, QRect(xy, box)) p.end() clipPath = QPainterPath() clipPath.addEllipse(QPointF(center), ring, ring) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) p.setClipPath(clipPath) p.drawPixmap(corner, self.zoomPixmap) p.setClipping(False) p.drawPixmap(corner, self.maskPixmap) p.setPen(Qt.gray) p.drawPath(clipPath) if self.invert: p = QPainter(self) p.setCompositionMode(QPainter.CompositionMode_Difference) p.fillRect(event.rect(), Qt.white) p.end() def timerEvent(self, event): if not self.zoomed: self.activateZoom() self.update() def mousePressEvent(self, event): if event.buttons() != Qt.LeftButton: return self.pressed = self.snapped = True self.pressPos = self.dragPos = event.pos() self.tapTimer.stop() self.tapTimer.start(HOLD_TIME, self) def mouseMoveEvent(self, event): if not event.buttons(): return if not self.zoomed: if not self.pressed or not self.snapped: delta = event.pos() - self.pressPos self.pressPos = event.pos() self._normalMap.pan(delta) return else: threshold = 10 delta = event.pos() - self.pressPos if self.snapped: self.snapped &= delta.x() < threshold self.snapped &= delta.y() < threshold self.snapped &= delta.x() > -threshold self.snapped &= delta.y() > -threshold if not self.snapped: self.tapTimer.stop() else: self.dragPos = event.pos() self.update() def mouseReleaseEvent(self, event): self.zoomed = False self.update() def keyPressEvent(self, event): if not self.zoomed: if event.key() == Qt.Key_Left: self._normalMap.pan(QPoint(20, 0)) if event.key() == Qt.Key_Right: self._normalMap.pan(QPoint(-20, 0)) if event.key() == Qt.Key_Up: self._normalMap.pan(QPoint(0, 20)) if event.key() == Qt.Key_Down: self._normalMap.pan(QPoint(0, -20)) if event.key() == Qt.Key_Z or event.key() == Qt.Key_Select: self.dragPos = QPoint(self.width() / 2, self.height() / 2) self.activateZoom() else: if event.key() == Qt.Key_Z or event.key() == Qt.Key_Select: self.zoomed = False self.update() delta = QPoint(0, 0) if event.key() == Qt.Key_Left: delta = QPoint(-15, 0) if event.key() == Qt.Key_Right: delta = QPoint(15, 0) if event.key() == Qt.Key_Up: delta = QPoint(0, -15) if event.key() == Qt.Key_Down: delta = QPoint(0, 15) if delta != QPoint(0, 0): self.dragPos += delta self.update()