def set_image(self, image_filename): size = 800 pixmap = QPixmap(image_filename) if pixmap.width() > pixmap.height(): if pixmap.width() > size: pixmap = pixmap.scaledToWidth(size) else: if pixmap.height() > size: pixmap = pixmap.scaledToHeight(size) self.ui.label.setPixmap(pixmap) self.ui.label.setMask(pixmap.mask()) self.ui.label.show()
def draw_indicator(indicator: int): pixmap = QPixmap(24, 24) painter = QPainter(pixmap) w, h = pixmap.width(), pixmap.height() painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255)))) pen = QPen(QColor("white")) pen.setWidth(2) painter.setPen(pen) font = util.get_monospace_font() font.setBold(True) font.setPixelSize(16) painter.setFont(font) f = QFontMetrics(painter.font()) indicator_str = str(indicator) if indicator < 10 else "+" fw = f.width(indicator_str) fh = f.height() painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str) painter.end() return QIcon(pixmap)
def buildCharPreview(self): char = self.selectedChar - self.charFrom.value() if char < 0: char = 0 if char >= len(self.charSizes): char = len(self.charSizes) - 1 k = 5 s_x = self.charSizes[char][0] w = self.charSizes[char][1] charPix = self.chars.pixmap() charImage = charPix.toImage() self.charPreview.resize(w * k + 1, charPix.height() * k + 1) pix = QPixmap(w * k, charPix.height() * k) p = QPainter() p.begin(pix) p.setBrush(QBrush(QColor(0xffffff), Qt.SolidPattern)) p.drawRect(0, 0, pix.width() - 1, pix.height() - 1) p.setBrush(QBrush(QColor(0x0), Qt.SolidPattern)) for x in range(w): for y in range(charPix.height()): if QColor(charImage.pixel(s_x + x, y)).lightness() == 0x0: p.drawRect(x * k, y * k, k, k) p.end() self.charPreview.setPixmap(pix)
def createThemePreview(theme, screenRect, size=QSize(200, 120)): if type(theme) == str and os.path.exists(theme): # Theme is the path to an ini file themeDatas = loadThemeDatas(theme) else: themeDatas = theme pixmap = generateTheme(themeDatas, screenRect) addThemePreviewText(pixmap, themeDatas, screenRect) px = QPixmap(pixmap).scaled(size, Qt.KeepAspectRatio) w = px.width() / 10 h = px.height() / 10 r = themeTextRect(themeDatas, screenRect) painter = QPainter(px) painter.drawPixmap(QRect(w, h, w * 4, h * 5), pixmap, QRect(r.topLeft() - QPoint(w / 3, h / 3), QSize(w * 4, h * 5))) painter.setPen(Qt.white) painter.drawRect(QRect(w, h, w * 4, h * 5)) painter.end() return px
def drawRects(self, source, rectsTree, scale): """Draw rectangles in 'rectsTree' on 'source'. """ pixmap = QPixmap(source) self.drawBackground(pixmap) def drawRect(node, parentHash): painter = QtGui.QPainter(pixmap) roi, param, tracking = node.data x, y, w, h = common.scaleRect(roi, scale) painter.setPen(param.color) funcTable = { self.FILL_MASK: self.fillMask, self.FILL_BLUR: self.fillBlur, self.FILL_IMAGE: self.fillImage, self.FILL_COLOR: self.fillColor, self.FILL_OUTLINE: self.fillOutline } for fill, func in funcTable.iteritems(): if param.fill == fill: func(pixmap, painter, (x, y, w, h), param, source) if param.tracking: self.drawTracking(painter, tracking, scale) if param.showName: painter.drawText(x, y, param.name) return param.hash h, w = pixmap.height(), pixmap.width() rectsTree.map(None, drawRect) painter = QtGui.QPainter(source) painter.drawPixmap(0, 0, pixmap)
def paintEvent(self,event=None): painter = QPainter(self) pixmap=QPixmap(":/images/wheelfinal.png") #painter.begin(self) #painter.drawPixmap(QtCore.QRect(self.left, self.top, self.width, self.height), self.pixmap) painter.drawPixmap(self.rect(), pixmap) self.resize(pixmap.width(),pixmap.height()) pen = QPen(Qt.red, 3) painter.setPen(pen) painter.drawArc (self.disc_center-int(self.distance_from_center(self.points[0])) , self.disc_center - int(self.distance_from_center (self.points[0])) , 2*int(self.distance_from_center(self.points[0])) , 2*int(self.distance_from_center(self.points[0])) , int(16*self.hue_min) , int(16*(self.hue_max-self.hue_min)))#arc joining point 0 and point 1 painter.drawLine(int(self.points[0][0]),int(self.points[0][1]),int(self.points[3][0]),int(self.points[3][1]))#line joining point 0 and point 3 painter.drawArc(self.disc_center-int(self.distance_from_center(self.points[2])) , self.disc_center - int(self.distance_from_center (self.points[2])) , 2*int(self.distance_from_center(self.points[2])) , 2*int(self.distance_from_center(self.points[2])) , int(16*self.hue_min) , int(16*(self.hue_max-self.hue_min)))#arc joining point 2 and 3 painter.drawLine(int(self.points[1][0]),int(self.points[1][1]),int(self.points[2][0]),int(self.points[2][1]))#line joining point 1 and 2 self.update()
def _setup_layout(self): main_layout = QVBoxLayout() content_layout = QHBoxLayout() splash_path = os.path.join( os.path.split(ilastik.__file__)[0], 'ilastik-splash.png' ) splash_pixmap = QPixmap(splash_path) logo_label = QLabel() logo_label.setPixmap(splash_pixmap) content_layout.addWidget(logo_label) text_label = QLabel() text_label.setWordWrap(True) text_label.setTextFormat(Qt.RichText) text_label.setOpenExternalLinks(True) text_label.setText(about_text) content_layout.addWidget(text_label) btn_box = QDialogButtonBox(QDialogButtonBox.Ok) btn_box.accepted.connect(self.accept) main_layout.addLayout(content_layout) main_layout.addWidget(btn_box) self.setLayout(main_layout) self.setStyleSheet("background-color: white;") self.setWindowTitle('About ilastik') self.setFixedSize(splash_pixmap.width() * 2.5, splash_pixmap.height() * 1.05)
def __init_ui(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) label = QLabel(self) image = QPixmap('15_flower.jpg') label.setPixmap(image) label.move(0, 0) self.resize(image.width(), image.height())
class PlayerUI(ShapeUI): def __init__(self, parent, game): super().__init__(parent, game) self.player = game.player self.speed = game.player_speed self.pixmap = QPixmap("images/smile3.png") self.image_height_fix = 48 # 48 self.width = self.pixmap.width() self.height = self.pixmap.height() self.set_shape_size() self.set_initial_position() self.show() def set_initial_position(self): """Set the initial position of the player and moves the player there. """ self.x = (self.field_width - self.image_size[0]) / 2 self.y = self.field_height - 50 self.move(self.x, self.y) @property def is_player_invincible(self): """Checks if the player is invincible""" return self.player.is_player_invincible def set_player_invinciblity(self): """Sets the player's invincibility to the opposite of the current value. """ self.player.set_player_invinciblity() @pyqtSlot() def move_left(self): """Moves the player to the left and checks if the move is valid (if the move is out of the game field). """ print("left") if(self.x - self.speed > 0): self.x -= self.speed self.move(self.x, self.y) @pyqtSlot() def move_right(self): """Moves the player to the right and checks if the move is valid (if the move is out of the game field). """ print("right") if(self.x + self.speed < self.field_width - self.image_size[0]): self.x += self.speed self.move(self.x, self.y)
class ShapeWidget(QWidget): def __init__(self,parent=None): super(ShapeWidget,self).__init__(parent) self.i = 1 self.mypix() self.timer = QTimer() self.timer.setInterval(500) # 500毫秒 self.timer.timeout.connect(self.timeChange) self.timer.start() # 显示不规则 pic def mypix(self): self.update() if self.i == 5: self.i = 1 self.mypic = {1: './images/left.png', 2: "./images/up.png", 3: './images/right.png', 4: './images/down.png'} self.pix = QPixmap(self.mypic[self.i], "0", Qt.AvoidDither | Qt.ThresholdDither | Qt.ThresholdAlphaDither) self.resize(self.pix.size()) self.setMask(self.pix.mask()) self.dragPosition = None def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.m_drag=True self.m_DragPosition=event.globalPos()-self.pos() event.accept() self.setCursor(QCursor(Qt.OpenHandCursor)) def mouseMoveEvent(self, QMouseEvent): if Qt.LeftButton and self.m_drag: self.move(QMouseEvent.globalPos()- self.m_DragPosition ) QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.m_drag=False self.setCursor(QCursor(Qt.ArrowCursor)) def paintEvent(self, event): painter = QPainter(self) painter.drawPixmap(0, 0, self.pix.width(),self.pix.height(),self.pix) # 鼠标双击事件 def mouseDoubleClickEvent(self, event): if event.button() == 1: self.i += 1 self.mypix() # 每500毫秒修改paint def timeChange(self): self.i += 1 self.mypix()
class RoundRectItem(QGraphicsObject): def __init__(self, bounds, color, parent=None): super(RoundRectItem, self).__init__(parent) self.fillRect = False self.bounds = QRectF(bounds) self.pix = QPixmap() self.gradient = QLinearGradient() self.gradient.setStart(self.bounds.topLeft()) self.gradient.setFinalStop(self.bounds.bottomRight()) self.gradient.setColorAt(0, color) self.gradient.setColorAt(1, color.darker(200)) self.setCacheMode(QGraphicsItem.ItemCoordinateCache) def setFill(self, fill): self.fillRect = fill self.update() def fill(self): return self.fillRect fill = pyqtProperty(bool, fill, setFill) def paint(self, painter, option, widget): painter.setPen(Qt.NoPen) painter.setBrush(QColor(0, 0, 0, 64)) painter.drawRoundedRect(self.bounds.translated(2, 2), 25.0, 25.0) if self.fillRect: painter.setBrush(QApplication.palette().brush(QPalette.Window)) else: painter.setBrush(self.gradient) painter.setPen(QPen(Qt.black, 1)) painter.drawRoundedRect(self.bounds, 25.0, 25.0) if not self.pix.isNull(): painter.scale(1.95, 1.95) painter.drawPixmap(-self.pix.width() / 2, -self.pix.height() / 2, self.pix) def boundingRect(self): return self.bounds.adjusted(0, 0, 2, 2) def pixmap(self): return QPixmap(self.pix) def setPixmap(self, pixmap): self.pix = QPixmap(pixmap) self.update()
def loadImage(self, path): self.markable_picture = QMarkablePicture(self) hbox = QHBoxLayout(self) picture = QPixmap(path) if picture.width() > self.maximumWidth(): picture = picture.scaledToWidth(self.maximumWidth()) if picture.height() > self.maximumHeight(): picture = picture.scaledToHeight(self.maximumHeight()) self.markable_picture.setPixmap(picture) hbox.addWidget(self.markable_picture) hbox.setContentsMargins(0, 0, 0, 0) self.setLayout(hbox)
def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) button = QPushButton('PyQt5 button', self) button.setToolTip('This is an example button') button.move(0,0) button.clicked.connect(self.on_click) # # Create widget label = QLabel(self) pixmap = QPixmap(os.path.join(full_mask_path, 'EN20160520L039-26_mask.jpg')) label.setPixmap(pixmap) self.resize(pixmap.width(),pixmap.height()) self.show()
def set_cursor_shape(self, shape): ''' Set the shape of cursor, the param shape should be one of the keys of the global variable cursor_shape_dict. ''' if cursor_shape_dict.get(shape): pix = QPixmap(cursor_shape_dict[shape]) if shape == "shape_start_cursor": cur = QCursor(pix, hotX=8, hotY=8) elif shape.startswith(CURSOR_SHAPE_COLOR_PEN_PREFIX): cur = QCursor(pix, hotX=0, hotY=pix.height()) else: cur = QCursor(pix, hotX=5, hotY=5) else: cur = QCursor(Qt.ArrowCursor) self.setCursor(cur)
class ImageToggleButton(ToggleButton): def __init__(self,imgId,img): super(ImageToggleButton, self).__init__() self.id = imgId self.pixMap = QPixmap(img) eliminateBackgroundColor(self.pixMap) self.backBrush = QBrush(QColor(img.pixel(0,0))) def paintEvent(self,event): super().paintEvent(event) painter = QPainter(self) painter.fillRect(4,4,frameWidth,frameHeight,self.backBrush) painter.drawPixmap(4+(frameWidth-self.pixMap.width())//2,4+(frameHeight-self.pixMap.height())//2,self.pixMap) if self.isChecked(): painter.setPen(self.checkedPen) painter.drawRect(3,3,self.width()-6,self.height()-6)
def createThemePreview(theme, screenRect, size=QSize(200, 120)): """ Generates a QPixmap preview for given theme. Theme can be either a string containing the filename of the ini file with the theme settings, or it can be a dict with the settings. If theme is a filename, the result is cached. """ # Checking whether theme is a string or dict if type(theme) == str and os.path.exists(theme): # Theme is the path to an ini file themeDatas = loadThemeDatas(theme) fromFile = True else: themeDatas = theme fromFile = False # Check if item is in cache if fromFile and theme in _thumbCache: if _thumbCache[theme][0] == themeDatas: return _thumbCache[theme][1] pixmap = generateTheme(themeDatas, screenRect) addThemePreviewText(pixmap, themeDatas, screenRect) px = QPixmap(pixmap).scaled(size, Qt.KeepAspectRatio) w = px.width() / 10 h = px.height() / 10 r = themeTextRect(themeDatas, screenRect) painter = QPainter(px) painter.drawPixmap(QRect(w, h, w * 4, h * 5), pixmap, QRect(r.topLeft() - QPoint(w / 3, h / 3), QSize(w * 4, h * 5))) painter.setPen(Qt.white) painter.drawRect(QRect(w, h, w * 4, h * 5)) painter.end() # If theme is a themefile, we keep it in cache if fromFile: _thumbCache[theme] = [themeDatas, px] return px
class QImageArea(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) def loadImage(self, path): self.picture_label = QLabel(self) hbox = QHBoxLayout(self) self.picture = QPixmap(path) self.picture_label.setPixmap(self.picture) hbox.addWidget(self.picture_label) hbox.setContentsMargins(0, 0, 0, 0) self.setLayout(hbox) def getImageWidth(self): return self.picture.width() def getImageHeight(self): return self.picture.height()
def setColor(self, color): if type(color)!=QColor: color = QColor(color) if (self.mColor == color or not color.isValid()): return self.mColor = color size = QSize(self.iconSize()) size.setWidth(size.width()-2) size.setHeight(size.height()-2) pixmap = QPixmap(size) pixmap.fill(self.mColor) painter = QPainter(pixmap) border = QColor(Qt.black) border.setAlpha(128) painter.setPen(border) painter.drawRect(0, 0, pixmap.width() - 1, pixmap.height() - 1) painter.end() self.setIcon(QIcon(pixmap)) self.colorChanged.emit(color)
def setSampleImage(self, pathToFile): self.graphicsView.hide() #clear scene self.graphicsScene.clear() #load file tmpImage = QImage(pathToFile) self.originalHeight = tmpImage.height() self.originalWidth = tmpImage.width() tmpPixmap = QPixmap(1) tmpPixmap.convertFromImage(tmpImage.scaledToWidth(300)) self.scaledHeight = tmpPixmap.height() self.scaledWidth = tmpPixmap.width() #add to scene and show self.graphicsScene.addPixmap(tmpPixmap) self.graphicsView.show()
def put_cv2_image(self, image, widget): height, width = image.shape[0:2] qImg = self.cv2toQImage(image) pixmap = QPixmap(qImg) if height > width: if height > self.preview_size: pixmap = pixmap.scaledToHeight(self.preview_size) else: if width > self.preview_size: pixmap = pixmap.scaledToWidth(self.preview_size) widget.setPixmap(pixmap) #give hints to DrawableLabel() and MyLabel() widget.perspective = self.perspective widget.focus = self.focus widget.slitpos = self.slitpos w = pixmap.width() h = pixmap.height() x = ( self.preview_size - w ) // 2 y = ( self.preview_size - h ) // 2 widget.geometry = x,y,w,h
def startDrag(self, supportedActions): item = self.currentItem() itemData = QByteArray() dataStream = QDataStream(itemData, QIODevice.WriteOnly) pixmap = QPixmap(item.data(Qt.UserRole)) location = item.data(Qt.UserRole+1) dataStream << pixmap << location mimeData = QMimeData() mimeData.setData('image/x-puzzle-piece', itemData) drag = QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(QPoint(pixmap.width()/2, pixmap.height()/2)) drag.setPixmap(pixmap) if drag.exec_(Qt.MoveAction) == Qt.MoveAction: if self.currentItem() is not None: self.takeItem(self.row(item))
def __init__(self, imagepath, binpath): super().__init__() QToolTip.setFont(QFont('SansSerif', 10)) self.setToolTip('This is a <b>QWidget</b> widget') self.imageLabel = QLabel(self) self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.overlay = Overlay(self.imageLabel, binpath) self.setCentralWidget(self.overlay) self.overlay.c.cropImage.connect(self.crop) #self.overlay.setSizePolicy(QSizePolicy.Maximum,QSizePolicy.Maximum) self.imagepath = imagepath image = QPixmap(imagepath) w = image.width() h = image.height() rec = QApplication.desktop().screenGeometry(); dsk_h = rec.height(); dsk_w = rec.width(); wdw_w = min(0.7 * dsk_w, w) # Window's width 85% of screen's size self.ratio = wdw_w / w # Storing the ratio for later use wdw_h = h * self.ratio # A simple proportion to get the height, because we want to mantain the aspect ratio image = image.scaled(wdw_w, wdw_h, transformMode=QtCore.Qt.SmoothTransformation) self.imageLabel.setPixmap(image) self.imageLabel.adjustSize() self.setGeometry(dsk_w/2 - wdw_w/2, dsk_h/2 - wdw_h/2, wdw_w, wdw_h) self.setWindowTitle('Tooltips') self.show()
def main(): app = QApplication(sys.argv) filename = os.path.join(os.path.dirname(__file__), "assets.db") create = not QFile.exists(filename) db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(filename) if not db.open(): QMessageBox.warning(None, "Asset Manager", ("Database Error: {0}" .format(db.lastError().text()))) sys.exit(1) splash = None if create: app.setOverrideCursor(QCursor(Qt.WaitCursor)) splash = QLabel() pixmap = QPixmap(":/assetmanagersplash.png") splash.setPixmap(pixmap) splash.setMask(pixmap.createHeuristicMask()) splash.setWindowFlags(Qt.SplashScreen) rect = app.desktop().availableGeometry() splash.move((rect.width() - pixmap.width()) / 2, (rect.height() - pixmap.height()) / 2) splash.show() app.processEvents() createFakeData() form = MainForm() form.show() if create: splash.close() app.processEvents() app.restoreOverrideCursor() app.exec_() del form del db
class PaintWidget(QWidget): def __init__(self, parent, model, pixel_size, vnc=None): super().__init__(parent) self.fb = FrameBuffer(model) self.pixel_size = pixel_size self.mPixmap = QPixmap() self.vnc = vnc def paintEvent(self, event): if self.fb.pixels: pixmap = QPixmap(self.size() / self.pixel_size) pixmap.fill(Qt.white) painter = QPainter(pixmap) painter.drawPixmap(0, 0, self.mPixmap) self._redraw(painter) self.mPixmap = pixmap self.fb.pixels = {} qp = QPainter(self) copied_pixmap = self.mPixmap if self.pixel_size != 1: # Only call scaled if needed. copied_pixmap = self.mPixmap.scaled( self.mPixmap.width() * self.pixel_size, self.mPixmap.height() * self.pixel_size) qp.drawPixmap(0, 0, copied_pixmap) def _redraw(self, qp): for (x, y), color in self.fb.pixels.items(): qp.setPen(QColor.fromRgb(color)) qp.drawPoint(x, y) if self.vnc: self.vnc.redraw(self.fb.pixels) def draw_point(self, x, y, color): return self.fb.draw_point(x, y, color)
def init(self): self.window = loadUi(os.path.join(get_ui_path(),"splash.ui")) self.window.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint) self.center() self.window.li.setText(notice()+"\n"+version()) self.window.setModal(Qt.WindowModal) self.window.image.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.window.image.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) window_h=self.window.height() window_w=self.window.width() r=random.randint(2, 3) image=QPixmap(os.path.join(get_image_file_path(),"splash"+str(r)+".png")) image.scaledToHeight(window_h) w=image.width() h=image.height() x_max=w-window_h-window_w/2 hour=float(time.strftime("%H"))*60 m=float(time.strftime("%m")) tot=hour+m my_max=float(24*60) value=tot/my_max xpos=int(x_max*value)+window_w/2 print("xpos=",xpos) scene=QGraphicsScene(); scene.setSceneRect(xpos, 0, 0, h) self.window.image.setScene(scene) self.window.show() scene.addPixmap(image); QTimer.singleShot(1500, self.callback_destroy)
def createTopGroupBox(self): self.topGroupBox = QGroupBox(self.title) self.topGroupBox.setAlignment(Qt.AlignHCenter) layout = QVBoxLayout() self.pushUpdateButton.setDefault(True) out = subprocess.Popen(['./appsAway_checkUpdates.sh'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = out.communicate() if b"true" in stdout: self.pushUpdateButton.setEnabled(True) self.pushUpdateButton.setText("Update Available") elif b"false" in stdout: self.pushUpdateButton.setEnabled(False) self.pushUpdateButton.setText("Everything is Up to Date!") layout.addWidget(self.pushUpdateButton) pixmap = QPixmap(self.image) if pixmap.height() > 250: pixmap = pixmap.scaledToHeight(250, Qt.SmoothTransformation) self.label.setPixmap(pixmap) #self.resize(pixmap.width(),pixmap.height()) #self.show() layout.addWidget(self.label) layout.addStretch(1) layout.setAlignment(Qt.AlignCenter) self.topGroupBox.setLayout(layout) self.pushUpdateButton.clicked.connect(self.startUpdate)
class RedimensionarImagem(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) super().setupUi(self) self.btnEscolherArquivo.clicked.connect(self.abrir_imagem) self.btnRedimensionar.clicked.connect(self.redimensionar) self.btnSalvar.clicked.connect(self.salvar) def abrir_imagem(self): imagem, _ = QFileDialog.getOpenFileName( self.centralwidget, # QUem é pai da caixa de Diálogo 'Abrir Imagem', # título da caixa de Diálogo 'C:\\Users\\desen\\Pictures\\', # caminho que ela vai inciar # options=QFileDialog.DontUseNativeDialog Se não quisar usar a caixa nativa do sistema ) self.edtAbrirArquivo.setText(imagem) self.orignal_img = QPixmap(imagem) self.lblImg.setPixmap(self.orignal_img) self.edtLargura.setText(str(self.orignal_img.width())) self.edtAltura.setText(str(self.orignal_img.height())) def redimensionar(self): largura = int(self.edtLargura.text()) self.nova_imagem = self.orignal_img.scaledToWidth( largura) # calcula altomatimente com base na largura passada self.lblImg.setPixmap(self.nova_imagem) self.edtLargura.setText(str(self.nova_imagem.width())) self.edtAltura.setText(str(self.nova_imagem.height())) def salvar(self): imagem, _ = QFileDialog.getSaveFileName( self.centralwidget, # QUem é pai da caixa de Diálogo 'Salvar Imagem', # título da caixa de Diálogo 'C:\\Users\\desen\\Pictures\\', # caminho que ela vai inciar # options=QFileDialog.DontUseNativeDialog Se não quisar usar a caixa nativa do sistema ) self.nova_imagem.save(imagem, 'PNG')
def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) poop_label = QLabel(self) self.show() input_str = input( "Please Input the Name of the Emoji you want to see:)) \n To Finish Process type 'finish' " ) while not input_str == "finish": input_str = input( "Please Input the Name of the Emoji you want to see:))") if input_str == "poop": poop = QPixmap('poop.png') poop_label.setPixmap(poop) self.resize(poop.width(), poop.height()) self.update() elif input_str == "smiley": smiley = QPixmap('smiley.png') poop_label.setPixmap(smiley) self.resize(smiley.width(), smiley.height()) self.update() elif input_str == "smirk": smirk = QPixmap('smirk.png') poop_label.setPixmap(smirk) self.resize(smirk.width(), smirk.height()) self.update() elif input_str == "surprised": surprised = QPixmap('surprised.png') poop_label.setPixmap(surprised) self.resize(surprised.width(), surprised.height()) self.update() elif input_str == "heart_eyes": heart_eyes = QPixmap('heart_eyes.png') poop_label.setPixmap(heart_eyes) self.resize(heart_eyes.width(), heart_eyes.height()) self.update() elif input_str == "crying": crying = QPixmap('crying.png') poop_label.setPixmap(crying) self.resize(crying.width(), crying.height()) self.update()
def update_label_object(self): # Showing text while image is loading and processing self.label.setText('Processing ...') # Opening dialog window to choose an image file # Giving name to the dialog window --> 'Choose Image to Open' # Specifying starting directory --> '.' # Showing only needed files to choose from --> '*.png *.jpg *.bmp' image_path = \ QtWidgets.QFileDialog.getOpenFileName(self, 'Choose Image to Open', '.', '*.png *.jpg *.bmp') # Variable 'image_path' now is a tuple that consists of two elements # First one is a full path to the chosen image file # Second one is a string with possible extensions # Checkpoint print(type(image_path)) # <class 'tuple'> print(image_path[0]) # /home/my_name/Downloads/example.png print(image_path[1]) # *.png *.jpg *.bmp # Slicing only needed full path image_path = image_path[0] # /home/my_name/Downloads/example.png # Opening image with QPixmap class that is used to # show image inside Label object pixmap_image = QPixmap(image_path) # Passing opened image to the Label object self.label.setPixmap(pixmap_image) # Getting opened image width and height # And resizing Label object according to these values self.label.resize(pixmap_image.width(), pixmap_image.height())
class PushButton(QPushButton): def __init__(self,parent = None): super(PushButton,self).__init__(parent) self.status = 0 def loadPixmap(self, pic_name): self.pixmap = QPixmap(pic_name) self.btn_width = self.pixmap.width()/4 self.btn_height = self.pixmap.height() self.setFixedSize(self.btn_width, self.btn_height) def enterEvent(self,event): self.status = 1 self.update() def mousePressEvent(self,event): self.mouse_press = True self.status = 2 self.update() def mouseReleaseEvent(self,event): if(self.mouse_press): self.mouse_press = False self.status = 3 self.update() self.clicked.emit(True) def leaveEvent(self,event): self.status = 0 self.update() def paintEvent(self,event): self.painter = QPainter() self.painter.begin(self) self.painter.drawPixmap(self.rect(), self.pixmap.copy(self.btn_width * self.status, 0, self.btn_width, self.btn_height)) self.painter.end()
def drawTextIcon( self, painter, image: QPixmap, shearX: float = 0, shearY: float = 0, iconX=0, iconY=0, textX=60, textY=21, fontSize=11, ): """ 绘制图标和文字 """ painter.shear(shearX, shearY) # 绘制图标 painter.drawPixmap(iconX, iconY, image.width(), image.height(), image) # 绘制文字 if self.text(): painter.setPen(QPen(Qt.black)) painter.setFont(QFont("Microsoft YaHei", fontSize, 25)) if self.objectName() not in ["myLoveButton", "playListButton"]: painter.drawText(textX, textY + 16, self.text()) else: painter.drawText(textX, textY + 18, self.text())
def initUI(self, image): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) label = QLabel(self) pixmap = QPixmap(image) label.setPixmap(pixmap) self.resize(pixmap.width(), pixmap.height()) button = QPushButton('I see positive', self) button.setToolTip('I see a fish') button.move(20, 70) button.clicked.connect(self.on_click) button = QPushButton('I see negative', self) button.setToolTip('This is an example button') button.move(150, 70) button.clicked.connect(self.on_click2) button = QPushButton('Exit', self) button.setToolTip('This is an example button') button.move(80, 200) button.clicked.connect(self.exit) self.show()
def place_minion(self, pos, tipo, size, iden, team): setattr(self, 'img_' + iden, MyQLabel(self)) qlabel = getattr(self, 'img_' + iden) qlabel.tamano = size path = 'IMGS/{}/{}_move0.png'.format(tipo, team) if path not in self.imagenes: img = QPixmap(path) img = img.scaled(size, size, Qt.KeepAspectRatio) self.imagenes[path] = img else: img = self.imagenes[path] diag = (img.width()**2 + img.height()**2)**0.5 qlabel.setMinimumSize(diag, diag) qlabel.setAlignment(Qt.AlignCenter) qlabel.setPixmap(img) qlabel.move(*pos) qlabel.show() setattr(self, 'emptylifebar_' + iden, MyQLabel(self)) img = self.imagenes['IMGS/emptybar_minions.png'] qlabel = getattr(self, 'emptylifebar_' + iden) qlabel.setPixmap(img) x, y = offsets[tipo] qlabel.offsets = (x, y) qlabel.move(pos[0] + x, pos[1] + y) qlabel.show() setattr(self, 'redbar_' + iden, MyQLabel(self)) img = self.imagenes['IMGS/redbar_minions.png'] qlabel = getattr(self, 'redbar_' + iden) qlabel.setPixmap(img) x, y = offsets[tipo] qlabel.move(pos[0] + x + 2, pos[1] + y + 2) qlabel.show()
def add_image(self, path: str, position: list, size: int) -> QLabel: """Add Image.""" if os.path.isfile(path): labelImage = QLabel(self.window) pixmap = QPixmap(path) # ensures the new label size will scale the image itself labelImage.setScaledContents(True) labelImage.setPixmap(pixmap) width = pixmap.width() height = pixmap.height() if width > height: new_width = size new_height = size * height / width else: new_height = size new_width = size * width / height labelImage.resize(new_width, new_height) labelImage.move(position[0], position[1]) self.images.append(labelImage) return labelImage raise Exception('Invalid path to image provided')
def __init__(self, resdir, width, height, toggle=True, tooltip=False, parent=None): super(ImageButton, self).__init__(parent) self.isHover = False self._states = [] self.currentState = 0 if toggle: tStates = 5 else: tStates = 4 for i in range(1, tStates): if os.path.isfile(os.path.join(resdir, str(i) + ".png")): _pixmap = QPixmap(os.path.join(resdir, str(i) + ".png")) w = min(width, _pixmap.width()) h = min(height, _pixmap.height()) self._states.append(_pixmap.scaled(w, h, Qt.KeepAspectRatio)) self.setFixedSize(width, height) if tooltip: self.setToolTip(tooltip)
def selectionChanged(self): row = self.tableWidget_T3.currentRow() g = self.tableWidget_T3.item(row, 2).text() d = tmdbConnect.movieDescription(g) self.label_Title_T3.setText(d[0]) self.label_Year_T3.setText(d[1]) if self.label_Description_T3.setText(d[2]) == '': print('Pas de description') else: self.label_Description_T3.setText(d[2]) if d[3] == None: self.label_Poster_T3.clear() self.label_Poster_T3.setText("Pas d'image") else: url = 'https://image.tmdb.org/t/p/w185/' + d[3] data = urllib.request.urlopen(url).read() image = QtGui.QImage() image.loadFromData(data) pixmap = QPixmap(image) self.label_Poster_T3.setPixmap(pixmap) self.label_Poster_T3.resize(pixmap.width(), pixmap.height())
def _drawPixmap(self, role: Role, size: QSize) -> None: pixmap = QPixmap(size) width, height = pixmap.width(), pixmap.height() pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) if role == self.Role.CHECKED: self.drawPixmapForChecked(painter, width, height) elif role == self.Role.UNCHECKED: self.drawPixmapForUnchecked(painter, width, height) elif role == self.Role.PARTIAL: self.drawPixmapForPartiallyChecked(painter, width, height) elif role == self.Role.MODE_3D: self.drawPixmapFor3d(painter, width, height) elif role == self.Role.MODE_2D: self.drawPixmapFor2d(painter, width, height) elif role == self.Role.DISABLED: pixmap.fill(Qt.white) else: raise NotImplementedError(f"{role}") return pixmap
class Resize(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) super().setupUi(self) self.btnEscolherArquivo.clicked.connect(self.open_image) self.btnRedimensionar.clicked.connect(self.resize_image) self.btnSalvar.clicked.connect(self.save) def open_image(self): image, _ = QFileDialog.getOpenFileName( self.centralwidget, "Open Image", "/home/anthrax/Pictures/", options=QFileDialog.DontUseNativeDialog, ) self.inputAbrirArquivo.setText(image) self.original_img = QPixmap(image) self.labelImg.setPixmap(self.original_img) self.inputLargura.setText(str(self.original_img.width())) self.inputAltura.setText(str(self.original_img.height())) def resize_image(self): height = int(self.inputLargura.text()) self.new_image = self.original_img.scaledToWidth(height) self.labelImg.setPixmap(self.new_image) self.inputLargura.setText(str(self.new_image.width())) self.inputAltura.setText(str(self.new_image.height())) def save(self): image, _ = QFileDialog.getSaveFileName( self.centralwidget, "Save Image", "/home/anthrax/Documents/", options=QFileDialog.DontUseNativeDialog, ) self.new_image.save(image, "PNG")
class QXImage(QFrame): def __init__(self, name, path, info, parent=None): super().__init__(parent=parent) self.name = name self.path = path self.info = info self.setupUI() def setupUI(self): self.hbox_layout = QHBoxLayout() self.setLayout(self.hbox_layout) self.label_main = QLabel(parent=self) self.image = QPixmap(self.path) self.label_main.setPixmap(self.image) self.hbox_layout.addWidget(self.label_main) self.label_name = QLabel(self.name) self.hbox_layout.addWidget(self.label_name) self.resize(self.image.width(), self.image.height()) def getInfo(self): return self.info
class Redimensionar(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) super().setupUi(self) self.btn_escolher_arquivo.clicked.connect(self.abrir_imagem) self.btn_redimensionar.clicked.connect(self.redimensionar) self.btn_salvar.clicked.connect(self.salver) def abrir_imagem(self): imagem, _ =QFileDialog.getOpenFileName( self.centralwidget, 'Abrir Imagem', r'C:\Users\gusta\Pictures', options=QFileDialog.DontUseNativeDialog ) self.input_abrir_arquivo.setText(imagem) self.original_img = QPixmap(imagem) self.label_img.setPixmap(self.original_img) self.input_largura.setText(str(self.original_img.width())) self.input_altura.setText(str(self.original_img.height())) def redimensionar(self): largura = int(self.input_largura.text()) self.nova_imagem = self.original_img.scaledToWidth(largura) self.label_img.setPixmap(self.nova_imagem) self.input_largura.setText(str(self.nova_imagem.width())) self.input_altura.setText(str(self.nova_imagem.height())) def salver(self): imagem, _ = QFileDialog.getSaveFileName( self.centralwidget, 'Salvar Imagem', r'C:\Users\gusta\Pictures', options=QFileDialog.DontUseNativeDialog ) self.nova_imagem.save(imagem, 'PNG')
class RedimensionarImagem(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) super().setupUi(self) self.btnEscolherArquivo.clicked.connect(self.abrir_imagem) self.btnRedimensionar.clicked.connect(self.redimensionar) self.btnSalvar.clicked.connect(self.salvar) def abrir_imagem(self): # _ -> descarta/desconsidera a váriavel/valor que seria atribuído ali imagem, _ = QFileDialog.getOpenFileName( self.centralwidget, 'Abrir imagem', r'/home/luizotavio/Imagens/', # r'' para não colocar 2 barras inv options=QFileDialog.DontUseNativeDialog # talvez nem precise ) self.inputAbrirArquivo.setText(imagem) # nome dado no qt designer self.original_img = QPixmap(imagem) self.labelImg.setPixmap(self.original_img) self.inputLargura.setText(str(self.original_img.width())) self.inputAltura.setText(str(self.original_img.height())) def redimensionar(self): largura = int(self.inputLargura.text()) self.nova_imagem = self.original_img.scaledToWidth(largura) self.labelImg.setPixmap(self.nova_imagem) self.inputLargura.setText(str(self.nova_imagem.width())) self.inputAltura.setText(str(self.nova_imagem.height())) def salvar(self): imagem, _ = QFileDialog.getSaveFileName( self.centralwidget, 'Salvar imagem', r'/home/luizotavio/Desktop/', options=QFileDialog.DontUseNativeDialog) self.nova_imagem.save(imagem, 'PNG')
def load_img(self, c): global counter counter += 1 imager = Imager(self.state["Title"], self.state["Artist"]) data = imager.get_data() if (c + 1 != counter): return pixmap = QPixmap() pixmap.loadFromData(data) map = QBitmap(pixmap.size()) map.fill(Qt.color0) painter = QPainter(map) painter.setBrush(Qt.color1) painter.drawRoundedRect(0, 0, pixmap.width(), pixmap.height(), 10, 10) painter.end() self.app.label.setScaledContents(True) pixmap.setMask(map) self.app.label.setPixmap( pixmap.scaled(self.app.label.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation))
def add_pic_fromData(self, data, boshowsize=True): if not data: return pixmap = None if isinstance(data, str): if os.path.isfile(data): pixmap = QPixmap(data) elif isinstance(data, bytes): pixmap = QPixmap() pixmap.loadFromData(data) if not pixmap: return icon = QIcon(pixmap) s_size = '' if boshowsize: s_size = '{}*{}'.format(pixmap.width(), pixmap.height()) item = QListWidgetItem(icon, self.tr(s_size)) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Checked) self.addItem(item) self.scrollToItem(item)
def initUI(self): xkcd_array = requests.get("http://dynamic.xkcd.com/api-0/jsonp/comic/").json() self.setGeometry(300, 300, 1000, 500) title = xkcd_array['title'].encode("latin-1").decode("utf-8") self.setWindowTitle('XKCD - '+title) print(type(title)) alt = xkcd_array['alt'].encode("latin-1").decode("utf-8") self.setToolTip(alt) url = xkcd_array['img'] data = urllib.request.urlopen(url).read() img = QPixmap() img.loadFromData(data) self.resize(img.width(), img.height()) lbl2 = QLabel('asd', self) lbl2.setPixmap(img) self.show()
class Redimensionamento(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) super().setupUi(self) # para que ele execute a instancia dessa classe self.btnEscolheArq.clicked.connect(self.abrir_imagem) self.btnRedim.clicked.connect(self.redimensionar) self.btnSalvar.clicked.connect(self.salvar) def abrir_imagem(self): image, _ = QFileDialog.getOpenFileName( self.centralwidget, 'Abrir imagem' '/home/adriana/Downloads/', # options=QFileDialog.DontUseNativeDialog #se nao funcionar a janela, descomentar essa parte ) self.inputArquivo.setText(image) self.original_img = QPixmap(image) self.labelImg.setPixmap(self.original_img) self.inputLargura.setText(str(self.original_img.width())) self.inputAltura.setText(str(self.original_img.height())) def redimensionar(self): largura = int(self.inputLargura.text()) self.nova_imagem = self.original_img.scaledToWidth( largura) # calcula a altura automaticamente self.labelImg.setPixmap(self.nova_imagem) self.inputLargura.setText(str(self.nova_imagem.width())) self.inputAltura.setText(str(self.nova_imagem.height())) def salvar(self): image, _ = QFileDialog.getSaveFileName( self.centralwidget, 'Salvar imagem' '/home/adriana/', ) self.nova_imagem.save(image)
def setBorderImage(self, obj, scale, source, repeat='stretched stretched'): # 获取图片尺寸 sourcePixmap = QPixmap(source) sourceWidth = sourcePixmap.width() sourceHeight = sourcePixmap.height() # print(sourceHeight, sourceWidth) slice = [0, 0, 0, 0] slice[0] = scale[1] # 上 slice[1] = sourceWidth - scale[2] # 右 if slice[1] < 0: slice[1] = 0 slice[2] = sourceHeight - scale[3] # 下 if slice[2] < 0: slice[2] = 0 slice[3] = scale[0] # 左 slice = ' '.join([str(i) for i in slice]) # print(slice) obj.setStyleSheet('padding:' + str(sourceHeight / 2) + ' -' + str(sourceWidth / 2) + ';border-width:' + slice + ';border-image:url(' + source + ') ' + slice + ' ' + repeat)
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.puzzleImage = QPixmap() self.setupMenus() self.setupWidgets() self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) self.setWindowTitle("Puzzle") def openImage(self, path=None): if not path: path, _ = QFileDialog.getOpenFileName( self, "Open Image", '', "Image Files (*.png *.jpg *.bmp)") if path: newImage = QPixmap() if not newImage.load(path): QMessageBox.warning(self, "Open Image", "The image file could not be loaded.", QMessageBox.Cancel) return self.puzzleImage = newImage self.setupPuzzle() def setCompleted(self): QMessageBox.information( self, "Puzzle Completed", "Congratulations! You have completed the puzzle!\nClick OK " "to start again.", QMessageBox.Ok) self.setupPuzzle() def setupPuzzle(self): size = min(self.puzzleImage.width(), self.puzzleImage.height()) self.puzzleImage = self.puzzleImage.copy( (self.puzzleImage.width() - size) / 2, (self.puzzleImage.height() - size) / 2, size, size).scaled(400, 400, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self.piecesList.clear() for y in range(5): for x in range(5): pieceImage = self.puzzleImage.copy(x * 80, y * 80, 80, 80) self.piecesList.addPiece(pieceImage, QPoint(x, y)) random.seed(QCursor.pos().x() ^ QCursor.pos().y()) for i in range(self.piecesList.count()): if random.random() < 0.5: item = self.piecesList.takeItem(i) self.piecesList.insertItem(0, item) self.puzzleWidget.clear() def setupMenus(self): fileMenu = self.menuBar().addMenu("&File") openAction = fileMenu.addAction("&Open...") openAction.setShortcut("Ctrl+O") exitAction = fileMenu.addAction("E&xit") exitAction.setShortcut("Ctrl+Q") gameMenu = self.menuBar().addMenu("&Game") restartAction = gameMenu.addAction("&Restart") openAction.triggered.connect(self.openImage) exitAction.triggered.connect(QApplication.instance().quit) restartAction.triggered.connect(self.setupPuzzle) def setupWidgets(self): frame = QFrame() frameLayout = QHBoxLayout(frame) self.piecesList = PiecesList() self.puzzleWidget = PuzzleWidget() self.puzzleWidget.puzzleCompleted.connect(self.setCompleted, Qt.QueuedConnection) frameLayout.addWidget(self.piecesList) frameLayout.addWidget(self.puzzleWidget) self.setCentralWidget(frame)
class MandelbrotWidget(QWidget): def __init__(self, parent=None): super(MandelbrotWidget, self).__init__(parent) self.thread = RenderThread() self.pixmap = QPixmap() self.pixmapOffset = QPoint() self.lastDragPos = QPoint() self.centerX = DefaultCenterX self.centerY = DefaultCenterY self.pixmapScale = DefaultScale self.curScale = DefaultScale self.thread.renderedImage.connect(self.updatePixmap) self.setWindowTitle("Mandelbrot") self.setCursor(Qt.CrossCursor) self.resize(550, 400) def paintEvent(self, event): painter = QPainter(self) painter.fillRect(self.rect(), Qt.black) if self.pixmap.isNull(): painter.setPen(Qt.white) painter.drawText(self.rect(), Qt.AlignCenter, "Rendering initial image, please wait...") return if self.curScale == self.pixmapScale: painter.drawPixmap(self.pixmapOffset, self.pixmap) else: scaleFactor = self.pixmapScale / self.curScale newWidth = int(self.pixmap.width() * scaleFactor) newHeight = int(self.pixmap.height() * scaleFactor) newX = self.pixmapOffset.x() + (self.pixmap.width() - newWidth) / 2 newY = self.pixmapOffset.y() + (self.pixmap.height() - newHeight) / 2 painter.save() painter.translate(newX, newY) painter.scale(scaleFactor, scaleFactor) exposed, _ = painter.matrix().inverted() exposed = exposed.mapRect(self.rect()).adjusted(-1, -1, 1, 1) painter.drawPixmap(exposed, self.pixmap, exposed) painter.restore() text = "Use mouse wheel or the '+' and '-' keys to zoom. Press and " \ "hold left mouse button to scroll." metrics = painter.fontMetrics() textWidth = metrics.width(text) painter.setPen(Qt.NoPen) painter.setBrush(QColor(0, 0, 0, 127)) painter.drawRect((self.width() - textWidth) / 2 - 5, 0, textWidth + 10, metrics.lineSpacing() + 5) painter.setPen(Qt.white) painter.drawText((self.width() - textWidth) / 2, metrics.leading() + metrics.ascent(), text) def resizeEvent(self, event): self.thread.render(self.centerX, self.centerY, self.curScale, self.size()) def keyPressEvent(self, event): if event.key() == Qt.Key_Plus: self.zoom(ZoomInFactor) elif event.key() == Qt.Key_Minus: self.zoom(ZoomOutFactor) elif event.key() == Qt.Key_Left: self.scroll(-ScrollStep, 0) elif event.key() == Qt.Key_Right: self.scroll(+ScrollStep, 0) elif event.key() == Qt.Key_Down: self.scroll(0, -ScrollStep) elif event.key() == Qt.Key_Up: self.scroll(0, +ScrollStep) else: super(MandelbrotWidget, self).keyPressEvent(event) def wheelEvent(self, event): numDegrees = event.angleDelta().y() / 8 numSteps = numDegrees / 15.0 self.zoom(pow(ZoomInFactor, numSteps)) def mousePressEvent(self, event): if event.buttons() == Qt.LeftButton: self.lastDragPos = QPoint(event.pos()) def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: self.pixmapOffset += event.pos() - self.lastDragPos self.lastDragPos = QPoint(event.pos()) self.update() def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.pixmapOffset += event.pos() - self.lastDragPos self.lastDragPos = QPoint() deltaX = (self.width() - self.pixmap.width()) / 2 - self.pixmapOffset.x() deltaY = (self.height() - self.pixmap.height()) / 2 - self.pixmapOffset.y() self.scroll(deltaX, deltaY) def updatePixmap(self, image, scaleFactor): if not self.lastDragPos.isNull(): return self.pixmap = QPixmap.fromImage(image) self.pixmapOffset = QPoint() self.lastDragPosition = QPoint() self.pixmapScale = scaleFactor self.update() def zoom(self, zoomFactor): self.curScale *= zoomFactor self.update() self.thread.render(self.centerX, self.centerY, self.curScale, self.size()) def scroll(self, deltaX, deltaY): self.centerX += deltaX * self.curScale self.centerY += deltaY * self.curScale self.update() self.thread.render(self.centerX, self.centerY, self.curScale, self.size())
import sys from PyQt5.QtWidgets import QApplication, QLabel, QWidget from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import QIcon, QPixmap app = QApplication(sys.argv) label = QLabel(app) pixmap = QPixmap('EYE.jpg') label.setPixmap(pixmap) label.resize(pixmap.width(), pixmap.height()) label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint) label.show() QTimer.singleShot(8000, app.quit) sys.exit(app.exec_())
class GridDelegate(QStyledItemDelegate): "A custom delegate for the model/view framework" POPUP = pyqtSignal() CONTEXT_ON = False # Gallery states G_NORMAL, G_DOWNLOAD = range(2) def __init__(self, parent=None): super().__init__(parent) QPixmapCache.setCacheLimit(app_constants.THUMBNAIL_CACHE_SIZE[0]* app_constants.THUMBNAIL_CACHE_SIZE[1]) self._painted_indexes = {} #misc.FileIcon.refresh_default_icon() self.file_icons = misc.FileIcon() if app_constants.USE_EXTERNAL_VIEWER: self.external_icon = self.file_icons.get_external_file_icon() else: self.external_icon = self.file_icons.get_default_file_icon() self.font_size = app_constants.GALLERY_FONT[1] self.font_name =0 # app_constants.GALLERY_FONT[0] if not self.font_name: self.font_name = QWidget().font().family() self.title_font = QFont() self.title_font.setBold(True) self.title_font.setFamily(self.font_name) self.artist_font = QFont() self.artist_font.setFamily(self.font_name) if self.font_size is not 0: self.title_font.setPixelSize(self.font_size) self.artist_font.setPixelSize(self.font_size) self.title_font_m = QFontMetrics(self.title_font) self.artist_font_m = QFontMetrics(self.artist_font) t_h = self.title_font_m.height() a_h = self.artist_font_m.height() self.text_label_h = a_h + t_h * 2 self.W = app_constants.THUMB_W_SIZE self.H = app_constants.THUMB_H_SIZE + app_constants.GRIDBOX_LBL_H#self.text_label_h #+ app_constants.GRIDBOX_LBL_H def key(self, key): "Assigns an unique key to indexes" if key in self._painted_indexes: return self._painted_indexes[key] else: k = hash(key) self._painted_indexes[key] = str(k) return str(k) def paint(self, painter, option, index): assert isinstance(painter, QPainter) if index.data(Qt.UserRole+1): if app_constants.HIGH_QUALITY_THUMBS: painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setRenderHint(QPainter.Antialiasing) gallery = index.data(Qt.UserRole+1) title = gallery.title artist = gallery.artist title_color = app_constants.GRID_VIEW_TITLE_COLOR artist_color = app_constants.GRID_VIEW_ARTIST_COLOR label_color = app_constants.GRID_VIEW_LABEL_COLOR # Enable this to see the defining box #painter.drawRect(option.rect) # define font size if 20 > len(title) > 15: title_size = "font-size:{}px;".format(self.font_size) elif 30 > len(title) > 20: title_size = "font-size:{}px;".format(self.font_size-1) elif 40 > len(title) >= 30: title_size = "font-size:{}px;".format(self.font_size-2) elif 50 > len(title) >= 40: title_size = "font-size:{}px;".format(self.font_size-3) elif len(title) >= 50: title_size = "font-size:{}px;".format(self.font_size-4) else: title_size = "font-size:{}px;".format(self.font_size) if 30 > len(artist) > 20: artist_size = "font-size:{}px;".format(self.font_size) elif 40 > len(artist) >= 30: artist_size = "font-size:{}px;".format(self.font_size-1) elif len(artist) >= 40: artist_size = "font-size:{}px;".format(self.font_size-2) else: artist_size = "font-size:{}px;".format(self.font_size) #painter.setPen(QPen(Qt.NoPen)) #option.rect = option.rect.adjusted(11, 10, 0, 0) option.rect.setWidth(self.W) option.rect.setHeight(self.H) rec = option.rect.getRect() x = rec[0] y = rec[1] w = rec[2] h = rec[3] text_area = QTextDocument() text_area.setDefaultFont(option.font) text_area.setHtml(""" <head> <style> #area {{ display:flex; width:{6}px; height:{7}px }} #title {{ position:absolute; color: {4}; font-weight:bold; {0} }} #artist {{ position:absolute; color: {5}; top:20px; right:0; {1} }} </style> </head> <body> <div id="area"> <center> <div id="title">{2} </div> <div id="artist">{3} </div> </div> </center> </body> """.format(title_size, artist_size, title, artist, title_color, artist_color, 130+app_constants.SIZE_FACTOR, 1+app_constants.SIZE_FACTOR)) text_area.setTextWidth(w) #chapter_area = QTextDocument() #chapter_area.setDefaultFont(option.font) #chapter_area.setHtml(""" #<font color="black">{}</font> #""".format("chapter")) #chapter_area.setTextWidth(w) def center_img(width): new_x = x if width < w: diff = w - width offset = diff//2 new_x += offset return new_x def img_too_big(start_x): txt_layout = misc.text_layout("Image is too big!", w, self.title_font, self.title_font_m) clipping = QRectF(x, y+h//4, w, app_constants.GRIDBOX_LBL_H - 10) txt_layout.draw(painter, QPointF(x, y+h//4), clip=clipping) # if we can't find a cached image pix_cache = QPixmapCache.find(self.key(gallery.profile)) if isinstance(pix_cache, QPixmap): self.image = pix_cache img_x = center_img(self.image.width()) if self.image.width() > w or self.image.height() > h: img_too_big(img_x) else: if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) else: self.image = QPixmap(gallery.profile) img_x = center_img(self.image.width()) QPixmapCache.insert(self.key(gallery.profile), self.image) if self.image.width() > w or self.image.height() > h: img_too_big(img_x) else: if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) # draw ribbon type painter.save() painter.setPen(Qt.NoPen) if app_constants.DISPLAY_GALLERY_RIBBON: type_ribbon_w = type_ribbon_l = w*0.11 rib_top_1 = QPointF(x+w-type_ribbon_l-type_ribbon_w, y) rib_top_2 = QPointF(x+w-type_ribbon_l, y) rib_side_1 = QPointF(x+w, y+type_ribbon_l) rib_side_2 = QPointF(x+w, y+type_ribbon_l+type_ribbon_w) ribbon_polygon = QPolygonF([rib_top_1, rib_top_2, rib_side_1, rib_side_2]) ribbon_path = QPainterPath() ribbon_path.setFillRule(Qt.WindingFill) ribbon_path.addPolygon(ribbon_polygon) ribbon_path.closeSubpath() painter.setBrush(QBrush(QColor(self._ribbon_color(gallery.type)))) painter.drawPath(ribbon_path) # draw if favourited if gallery.fav == 1: star_ribbon_w = star_ribbon_l = w*0.08 rib_top_1 = QPointF(x+star_ribbon_l, y) rib_side_1 = QPointF(x, y+star_ribbon_l) rib_top_2 = QPointF(x+star_ribbon_l+star_ribbon_w, y) rib_side_2 = QPointF(x, y+star_ribbon_l+star_ribbon_w) rib_star_mid_1 = QPointF((rib_top_1.x()+rib_side_1.x())/2, (rib_top_1.y()+rib_side_1.y())/2) rib_star_factor = star_ribbon_l/4 rib_star_p1_1 = rib_star_mid_1 + QPointF(rib_star_factor, -rib_star_factor) rib_star_p1_2 = rib_star_p1_1 + QPointF(-rib_star_factor, -rib_star_factor) rib_star_p1_3 = rib_star_mid_1 + QPointF(-rib_star_factor, rib_star_factor) rib_star_p1_4 = rib_star_p1_3 + QPointF(-rib_star_factor, -rib_star_factor) crown_1 = QPolygonF([rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3]) painter.setBrush(QBrush(QColor("yellow"))) painter.drawPolygon(crown_1) ribbon_polygon = QPolygonF([rib_top_1, rib_side_1, rib_side_2, rib_top_2]) ribbon_path = QPainterPath() ribbon_path.setFillRule(Qt.WindingFill) ribbon_path.addPolygon(ribbon_polygon) ribbon_path.closeSubpath() painter.drawPath(ribbon_path) #painter.setPen(QColor("#d35400")) #painter.drawPolyline(rib_top_1, rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3, rib_side_1) #painter.drawLine(rib_top_1, rib_top_2) #painter.drawLine(rib_top_2, rib_side_2) #painter.drawLine(rib_side_1, rib_side_2) painter.restore() if app_constants._REFRESH_EXTERNAL_VIEWER: if app_constants.USE_EXTERNAL_VIEWER: self.external_icon = self.file_icons.get_external_file_icon() else: self.external_icon = self.file_icons.get_default_file_icon() if gallery.state == self.G_DOWNLOAD: painter.save() dl_box = QRect(x, y, w, 20) painter.setBrush(QBrush(QColor(0,0,0,123))) painter.setPen(QColor('white')) painter.drawRect(dl_box) painter.drawText(dl_box, Qt.AlignCenter, 'Downloading...') painter.restore() else: if app_constants.DISPLAY_GALLERY_TYPE: self.type_icon = self.file_icons.get_file_icon(gallery.path) if self.type_icon and not self.type_icon.isNull(): self.type_icon.paint(painter, QRect(x+2, y+app_constants.THUMB_H_SIZE-16, 16, 16)) if app_constants.USE_EXTERNAL_PROG_ICO: if self.external_icon and not self.external_icon.isNull(): self.external_icon.paint(painter, QRect(x+w-30, y+app_constants.THUMB_H_SIZE-28, 28, 28)) def draw_text_label(lbl_h): #draw the label for text painter.save() painter.translate(x, y+app_constants.THUMB_H_SIZE) box_color = QBrush(QColor(label_color))#QColor(0,0,0,123)) painter.setBrush(box_color) rect = QRect(0, 0, w, lbl_h) #x, y, width, height painter.fillRect(rect, box_color) painter.restore() return rect if option.state & QStyle.State_MouseOver or\ option.state & QStyle.State_Selected: title_layout = misc.text_layout(title, w, self.title_font, self.title_font_m) artist_layout = misc.text_layout(artist, w, self.artist_font, self.artist_font_m) t_h = title_layout.boundingRect().height() a_h = artist_layout.boundingRect().height() if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(min(t_h+a_h+3, app_constants.GRIDBOX_LBL_H)) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) clipping = QRectF(x, y+app_constants.THUMB_H_SIZE, w, app_constants.GRIDBOX_LBL_H - 10) painter.setPen(QColor(title_color)) title_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE), clip=clipping) painter.setPen(QColor(artist_color)) artist_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE+t_h), clip=clipping) #painter.fillRect(option.rect, QColor) else: if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(self.text_label_h) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) # draw text painter.save() alignment = QTextOption(Qt.AlignCenter) alignment.setUseDesignMetrics(True) title_rect = QRectF(0,0,w, self.title_font_m.height()) artist_rect = QRectF(0,self.artist_font_m.height(),w, self.artist_font_m.height()) painter.translate(x, y+app_constants.THUMB_H_SIZE) if app_constants.GALLERY_FONT_ELIDE: painter.setFont(self.title_font) painter.setPen(QColor(title_color)) painter.drawText(title_rect, self.title_font_m.elidedText(title, Qt.ElideRight, w-10), alignment) painter.setPen(QColor(artist_color)) painter.setFont(self.artist_font) alignment.setWrapMode(QTextOption.NoWrap) painter.drawText(artist_rect, self.title_font_m.elidedText(artist, Qt.ElideRight, w-10), alignment) else: text_area.setDefaultFont(QFont(self.font_name)) text_area.drawContents(painter) ##painter.resetTransform() painter.restore() if option.state & QStyle.State_Selected: painter.save() selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(164,164,164,120))) painter.drawRoundedRect(selected_rect, 5, 5) #painter.fillRect(selected_rect, QColor(164,164,164,120)) painter.restore() if gallery.dead_link: painter.save() selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(255,0,0,120))) p_path = QPainterPath() p_path.setFillRule(Qt.WindingFill) p_path.addRoundedRect(selected_rect, 5,5) p_path.addRect(x,y, 20, 20) p_path.addRect(x+w-20,y, 20, 20) painter.drawPath(p_path.simplified()) painter.setPen(QColor("white")) txt_layout = misc.text_layout("Cannot find gallery source!", w, self.title_font, self.title_font_m) txt_layout.draw(painter, QPointF(x, y+h*0.3)) painter.restore() if app_constants.DEBUG: painter.save() painter.setBrush(QBrush(QColor("red"))) painter.setPen(QColor("white")) txt_l = self.title_font_m.width(str(gallery.id)) painter.drawRect(x, y+40, txt_l*2, self.title_font_m.height()) painter.drawText(x+1, y+51, str(gallery.id)) painter.restore() if option.state & QStyle.State_Selected: painter.setPen(QPen(option.palette.highlightedText().color())) else: super().paint(painter, option, index) def _ribbon_color(self, gallery_type): if gallery_type: gallery_type = gallery_type.lower() if gallery_type == "manga": return app_constants.GRID_VIEW_T_MANGA_COLOR elif gallery_type == "doujinshi": return app_constants.GRID_VIEW_T_DOUJIN_COLOR elif "artist cg" in gallery_type: return app_constants.GRID_VIEW_T_ARTIST_CG_COLOR elif "game cg" in gallery_type: return app_constants.GRID_VIEW_T_GAME_CG_COLOR elif gallery_type == "western": return app_constants.GRID_VIEW_T_WESTERN_COLOR elif "image" in gallery_type: return app_constants.GRID_VIEW_T_IMAGE_COLOR elif gallery_type == "non-h": return app_constants.GRID_VIEW_T_NON_H_COLOR elif gallery_type == "cosplay": return app_constants.GRID_VIEW_T_COSPLAY_COLOR else: return app_constants.GRID_VIEW_T_OTHER_COLOR def sizeHint(self, option, index): return QSize(self.W, self.H)
class MyApp(QWidget): def __init__(self, parent=None): super().__init__() self.initUI() self.lb_1 = QLabel() def initUI(self): grid = QGridLayout() self.setLayout(grid) # option 정하기 # 1열 self.checkbox1 = QCheckBox('Resize') self.checkbox2 = QCheckBox('rotate') self.checkbox3 = QCheckBox('hfip') self.checkbox4 = QCheckBox('vfip') self.checkbox5 = QCheckBox('rename') # pixmap 추가한내용 self.pixmap = QPixmap('/home/cj/Downloads/save.png') self.lbl_img = QLabel() self.lbl_img.setPixmap(self.pixmap) self.lbl_size = QLabel('Width: ' + str(self.pixmap.width()) + ', Height: ' + str(self.pixmap.height())) self.lbl_size.setAlignment(Qt.AlignCenter) grid.addWidget(self.checkbox1, 0, 0) self.checkbox1.stateChanged.connect(self.image_resize) grid.addWidget(self.checkbox2, 1, 0) self.checkbox2.stateChanged.connect(self.image_rotation) grid.addWidget(self.checkbox3, 2, 0) self.checkbox3.stateChanged.connect(self.image_hflip) grid.addWidget(self.checkbox4, 3, 0) self.checkbox4.stateChanged.connect(self.image_vflip) grid.addWidget(self.checkbox5, 4, 0) self.checkbox5.stateChanged.connect(self.image_rename) grid.addWidget(QLabel('PATH'), 6, 0) grid.addWidget(self.lbl_img, 7, 0) # 2열 self.ReSize_A = QLineEdit() self.ReSize_A.setAcceptDrops(False) grid.addWidget(self.ReSize_A, 0, 1) self.ReSize_A.returnPressed.connect(self.input_mask_changed) self.RoTate = QLineEdit() self.RoTate.setAcceptDrops(False) grid.addWidget(self.RoTate, 1, 1) self.RoTate.returnPressed.connect(self.input_mask_change2) grid.addWidget(QLabel('prefix'), 4, 1) self.prefix = QLineEdit() self.prefix.setAcceptDrops(False) grid.addWidget(self.prefix, 5, 1) self.prefix.returnPressed.connect(self.image_show) self.path = QLineEdit() self.path.setAcceptDrops(False) grid.addWidget(self.path, 6, 1, 1, 3) self.path.returnPressed.connect(self.image_show) # 3열 grid.addWidget(QLabel('number'), 5, 2) # 4열 self.btn = QPushButton('RUN') self.btn.clicked.connect(self.image_show) grid.addWidget(self.btn, 0, 3, 3, 1) # 크기 수정해야함 grid.addWidget(QLabel('suffix'), 4, 3) self.suffix = QLineEdit() grid.addWidget(self.suffix, 5, 3) self.setWindowTitle('Type Here') self.setGeometry(300, 300, 480, 320) self.show() def image_show(self): self.search_image = '/home/cj/Downloads/' + self.path.text() self.pixmap = QPixmap(self.search_image) self.lbl_size = QLabel('Width: ' + str(self.pixmap.width()) + ', Height: ' + str(self.pixmap.height())) self.lbl_size.setAlignment(Qt.AlignCenter) #click 시 checkbox 확인인 #사이즈 수정 if self.checkbox1.isChecked() == True: ##pixmap + cv2 활용 img = cv2.imread(self.search_image) reresize = float(self.ReSize_A.text()) self.resize_Img = cv2.resize(img, dsize=(0, 0), fx=reresize, fy=reresize, interpolation=cv2.INTER_LINEAR) cv2.imwrite("test.jpg", self.resize_Img) self.pixmap.load("test.jpg") # 각도회전 if self.checkbox2.isChecked() == True: src = cv2.imread(self.search_image, cv2.IMREAD_COLOR) height, width, channel = src.shape rorotation = float(self.RoTate.text()) matrix = cv2.getRotationMatrix2D((width / 2, height / 2), rorotation, 1) rotation_Img = cv2.warpAffine(src, matrix, (width, height)) cv2.imwrite("rotation.jpg", rotation_Img) self.pixmap.load("rotation.jpg") if self.checkbox3.isChecked() == True: im = cv2.imread(self.search_image) # im2 = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) im2_hflip = cv2.flip(im, 0) cv2.imwrite("im_hflip.jpg", im2_hflip) self.pixmap.load("im_hflip.jpg") if self.checkbox4.isChecked() == True: im = cv2.imread(self.search_image) im_vflip = cv2.flip(im, 1) cv2.imwrite("im_vflip.jpg", im_vflip) self.pixmap.load("im_vflip.jpg") if self.checkbox5.isChecked() == True: print('checkbox5 click') self.savefile() self.lbl_img.setPixmap(self.pixmap) # 이미지 보여주는 줄 print('run click') # 사이즈 수정함수 def image_resize(self): if self.checkbox1.isChecked() == True: self.input_mask_changed() def input_mask_changed(self): self.ReSize_A.setInputMask('0.0') # 사진 각도변경 def image_rotation(self): if self.checkbox2.isChecked() == True: self.input_mask_change2() def input_mask_change2(self): self.RoTate.setInputMask('000') # hflip 함수 def image_hflip(self): print('hflip click') # vflip 함수 def image_vflip(self): print('vflip click2') # rename 함수 def image_rename(self): print('rename click') def savefile(self): self.search_image = '/home/cj/Downloads/' name, _ = QFileDialog.getSaveFileName( self, self.search_image, options=QFileDialog.DontUseNativeDialog) cv2.imwrite(name, self.resize_Img)
class Scene(QGraphicsScene): _bbox_pen = None _bbox_start_pos = None _default_class = None _guide_pen = None _image = None _img_h = None _img_w = None _label_path = None _model = None _mouse_pos = None def __init__(self, parent): super().__init__(parent) self._guide_pen = QPen(Qt.black, 1) self.setDefaultClass(0) def saveLabels(self): if self._label_path != None: if self._label_path.endswith(".jpg.txt"): self._label_path = self._label_path[:-8] + ".txt" lf = QSaveFile(self._label_path) if not lf.open(QIODevice.WriteOnly | QIODevice.Text): raise IOError('Cannot open "{}" for writing'.format( self._label_path)) for item in self.items(): if item.type() == BBOX: rect = item.rect() c = item.number x = (rect.x() + rect.width() / 2) / self._img_w y = (rect.y() + rect.height() / 2) / self._img_h w = rect.width() / self._img_w h = rect.height() / self._img_h line = '{c:d} {x:.10f} {y:.10f} {w:.10f} {h:.10f}\n'.format( c=c, x=x, y=y, w=w, h=h) lf.write(line.encode()) if lf.commit(): print('Wrote "{}"'.format(self._label_path)) else: raise IOError('Cannot write "{}"'.format(self._label_path)) def _addBBox(self, p1, p2, cls): rect = _mkRectF(p1, p2).intersected(QRectF(self._image.rect())) square = abs(rect.width() * rect.height()) if square > 0.0: zvalue = 1.0 / square bbox = BoundingBoxItem(cls, rect, self._model) bbox.setZValue(zvalue) self.addItem(bbox) return True else: return False def _newBBox(self, p1, p2): if self._addBBox(p1, p2, self._default_class): self.invalidate() self.saveLabels() def setDefaultClass(self, cls): self._default_class = cls if self._model != None: (hue, sat, val) = self._model.hsvF(self._default_class) self._bbox_pen = QPen(QColor.fromHsvF(hue, sat, val), 2) def mouseMoveEvent(self, event): self._mouse_pos = event.scenePos() self.invalidate() super().mouseMoveEvent(event) def mousePressEvent(self, event): pos = event.scenePos() self._bbox_start_pos = pos def mouseReleaseEvent(self, event): if self._bbox_start_pos != None: self._newBBox(self._bbox_start_pos, event.scenePos()) self._bbox_start_pos = None self._mouse_pos = None def mouseDoubleClickEvent(self, event): item = self.itemAt(event.scenePos(), QTransform()) if item != None and item.type() == BBOX: self.removeItem(item) self.invalidate() self.saveLabels() def drawForeground(self, painter, rect): if self._mouse_pos != None: if self._bbox_start_pos == None: painter.setClipRect(rect) painter.setPen(self._guide_pen) painter.drawLine(self._mouse_pos.x(), rect.top(), self._mouse_pos.x(), rect.bottom()) painter.drawLine(rect.left(), self._mouse_pos.y(), rect.right(), self._mouse_pos.y()) else: painter.setPen(self._bbox_pen) painter.drawRect( _mkRectF(self._bbox_start_pos, self._mouse_pos)) def loadImage(self, image_path, label_path): self.clear() self._image = QPixmap(image_path) self._label_path = label_path[:-8] + ".txt" """ if not label_path.endswith(".jpg.txt"): self._label_path = label_path[:-8] + ".txt" else: self._label_path = label_path """ self.setSceneRect(QRectF(self._image.rect())) self.addPixmap(self._image) lines = [] self._img_h = self._image.height() self._img_w = self._image.width() try: with open(self._label_path) as lbl: lines = lbl.readlines() except OSError as ex: if ex.errno != errno.ENOENT: raise for l in lines: m = labeler.BBOX_RE.match(l) if m != None: cls = int(m.group('cls')) x = float(m.group('x')) y = float(m.group('y')) h = float(m.group('h')) w = float(m.group('w')) p1 = QPointF((x - w / 2) * self._img_w, (y - h / 2) * self._img_h) p2 = QPointF((x + w / 2) * self._img_w, (y + h / 2) * self._img_h) self._addBBox(p1, p2, cls) self.invalidate() @property def model(self): return self._model def setModel(self, model): self._model = model self.setDefaultClass(0)
class MainWindow(QMainWindow, Ui_MainWindow, QObject): all_points_given_signal = pyqtSignal( ) # Pravi se signal koji će biti korišćen da obavesti kada se unesu sve tačke def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.beforeDots = [] # Niz tačaka slike pre otklanjanja distorzije self.afterDots = [] # Niz tačaka druge slike self.num_of_dots = 0 # Broj tačaka koji će biti korišćen ( unosi korisnik ) self.first = False self.second = False self.setupUi(self) self.original_file = "" self.imageBefore = QPixmap() # Učitana slika čuva se kao mapa piksela self.imageAfter = QPixmap( ) # Slika koju pravi algoritam čuva se kao mapa piksela # Koriste se za crtanje tacaka na slikama self.painterBefore = QPainter() self.painterAfter = QPainter() self.init_gui() self.init_menu() def init_gui(self): self.labelBefore.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.labelAfter.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.labelBefore.mousePressEvent = self.get_pos self.labelAfter.mousePressEvent = self.get_pos self.get_num_of_dots() self.all_points_given_signal.connect( self.get_dots) # Na signal poziva se funkcija get_dots self.loadButton.pressed.connect( self.load ) # Na klik na dugme "Učitaj sliku" poziva se funkcija load self.workButton.pressed.connect( self.work) # Na klik na dugme "Primeni" poziva se funkcija work def init_menu(self): # Pritiskom na Esc ili u padajućem meniju na Izlaz izlazi se iz programa self.actionExit.triggered.connect(sys.exit) # Pritiskom na Ctrl + S ili u padajućem meniju na sačuvaj sliku čuva se slika dobijena iz algoritma self.actionSave.triggered.connect(self.save) def get_num_of_dots(self): num, ok = QInputDialog.getInt( self, "Broj tačaka", "Unesite broj tačaka koji će biti korišćen: ( >= 4 )") if ok and num >= 4: self.num_of_dots = num else: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Greška") msg.setText("Broj tačaka mora biti >= 4!") msg.exec_() sys.exit() def load(self): file, _ = QFileDialog(self).getOpenFileName(self, "Open file", "", "Image files (*.bmp)") filename, file_extension = os.path.splitext(file) if file_extension != ".bmp": msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Greška") msg.setText("Učitana slika mora biti u .bmp formatu!") msg.exec_() return self.imageBefore = QPixmap( filename) # Učitava se slika kao mapa piksela self.original_file = filename if not self.imageBefore.isNull(): # Postavlja se slika u okvir na prozoru za prikaz self.labelBefore.setPixmap( self.imageBefore.scaled( QSize(self.labelBefore.width(), self.labelBefore.height()))) # Postavlja se da se slika uveličava i smanjuje sa labelom self.labelBefore.setScaledContents(True) # Pravi se crna slika koja će se upisati u okvir za novu sliku self.imageAfter = QPixmap(self.imageBefore.width(), self.imageBefore.height()) self.imageAfter.fill(QColor("black")) self.labelAfter.setPixmap( self.imageAfter.scaled( QSize(self.labelAfter.width(), self.labelAfter.height()))) # Postavlja se da se slika uveličava i smanjuje sa labelom self.labelAfter.setScaledContents(True) self.painterBefore = QPainter(self.imageBefore) self.painterBefore.setBrush(QBrush(Qt.blue)) self.painterAfter = QPainter(self.imageAfter) self.painterAfter.setBrush(QBrush(Qt.red)) self.first = True # Omogučava se kliktanje po prvoj slici self.loadButton.setEnabled(False) self.get_dots() # Poziva se funkcija za prikupljanje tačaka def get_dots(self): msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Unos tačaka") # Ako je omogučeno kliktanje po prvoj slici if self.first: # Ovde se samo proverava broj tačaka da bi se gramatički tačno ispisala poruka :) if self.num_of_dots == 4: msg.setText("Unesite 4 tačke prve slike: ") else: msg.setText("Unesite " + str(self.num_of_dots) + " tačaka prve slike: ") msg.exec_() self.label.setText( self.label.text() + "\n" + "- Tačke prve slike: ( Ispisuju se u odnosu na original )\n") # Ako je omogučeno kliktanje po drugoj a onemogućeno kliktanje po prvoj slici elif not self.first and self.second: # Ovde se samo proverava broj tačaka da bi se gramatički tačno ispisala poruka :) if self.num_of_dots == 4: msg.setText("Unesite 4 tačke druge slike: ") else: msg.setText("Unesite " + str(self.num_of_dots) + " tačaka druge slike: ") msg.exec_() self.label.setText( self.label.text() + "\n" + "- Tačke druge slike: ( Ispisuju se u odnosu na original )\n") else: # Ako je unet dovoljan broj tačaka omogučava se dugme za primenu algoritama if len(self.beforeDots) == self.num_of_dots and len( self.afterDots) == self.num_of_dots: self.workButton.setEnabled(True) self.painterAfter.end() def work(self): if self.naiveAlgorithm.isChecked(): P = naive_algorithm(self.beforeDots, self.afterDots) P_inv = la.inv(P) elif self.dltAlgorithm.isChecked(): P = show_dlt(self.beforeDots, self.afterDots) P_inv = la.inv(P) elif self.dltNormAlgorithm.isChecked(): P = show_normalized(self.beforeDots, self.afterDots) P_inv = la.inv(P) else: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Greška") msg.setText("Izaberite algoritam!") msg.exec_() return imgBefore = QImage(self.original_file) imgAfter = QPixmap(self.imageBefore.width(), self.imageBefore.height()) imgAfter.fill(QColor("black")) imgAfter = imgAfter.toImage() for i in tqdm(range(imgBefore.width())): for j in range(imgBefore.height()): pixel = P_inv.dot(np.array([i, j, 1])) if pixel[0] < 0 or pixel[0] >= self.imageBefore.width(): continue if pixel[1] < 0 or pixel[1] >= self.imageBefore.height(): continue pix = imgBefore.pixelColor(pixel[0], pixel[1]) imgAfter.setPixel(i, j, pix.rgb()) self.imageAfter = QPixmap.fromImage(imgAfter) self.labelAfter.setPixmap( self.imageAfter.scaled( QSize(self.labelAfter.width(), self.labelAfter.height()))) self.workButton.setEnabled(False) def get_pos(self, event): if self.first: x = event.pos().x() y = event.pos().y() # Skaliraju se koordinate da bi se dobile koordinate početne slike S_x = self.imageBefore.width() / self.labelBefore.width() x = x * S_x S_y = self.imageBefore.height() / self.labelBefore.height() y = y * S_y self.painterBefore.drawEllipse(x - 5, y - 5, 10, 10) self.labelBefore.setPixmap( self.imageBefore.scaled( QSize(self.labelBefore.width(), self.labelBefore.height()))) self.beforeDots.append((x, y, 1)) self.label.setText(self.label.text() + " " + str((round(x), round(y)))) elif self.second: x = event.pos().x() y = event.pos().y() # Skaliraju se koordinate da bi se dobile koordinate krajnje slike bez skaliranja da stane u prozor S_x = self.imageAfter.width() / self.labelAfter.width() x = x * S_x S_y = self.imageAfter.height() / self.labelAfter.height() y = y * S_y self.painterAfter.drawEllipse(x - 5, y - 5, 10, 10) self.labelAfter.setPixmap( self.imageAfter.scaled( QSize(self.labelAfter.width(), self.labelAfter.height()))) self.afterDots.append((x, y, 1)) self.label.setText(self.label.text() + " " + str((round(x), round(y)))) # Ako se unese dovoljno prvih tačaka traži se isti broj drugih if len(self.beforeDots) == self.num_of_dots and self.first: self.first = False self.second = True self.labelBefore.mousePressEvent = self.empty_func self.all_points_given_signal.emit() if len(self.afterDots) == self.num_of_dots and self.second: self.second = False self.all_points_given_signal.emit() def empty_func(self, event): pass def save(self): # Čuva se dobijena slika file, file_type = QFileDialog(self).getSaveFileName( self, "Save file", "", "BMP (*.bmp);;PNG (*.png);;JPEG (*.jpeg)") filename, file_extension = os.path.splitext(file) if file_extension == "": if file_type == "BMP (*.bmp)": file_extension = ".bmp" elif file_type == "PNG (*.png)": file_extension = ".png" elif file_type == "JPEG (*.jpeg)": file_extension = ".jpeg" if file_extension == ".bmp" or file_extension == ".png" or file_extension == ".jpeg": self.imageAfter.save(file) QMessageBox.about(self, "Informacija", "Slika sačuvana.") else: QMessageBox.about( self, "Informacija", "Slika ne može biti sačuvana! ( Proveriti tip fajla... )")
class mywindow(QtWidgets.QMainWindow): def __init__(self): super(mywindow, self).__init__() print(session.evaluate('''Directory[]''')) self.imageQuestion = False self.setFixedSize(1200,700) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.white = False self.textcolor = "white" self.bg = self.palette().window().color() self.cl = (self.bg.redF(),self.bg.greenF(), self.bg.blueF()) # Makes the color of the textbox the same as the app if self.cl[0] > 0.5 and self.cl[1] > 0.5 and self.cl[2] >0.5: self.white = True self.textcolor = "black" # https://stackoverflow.com/questions/41247109/pyqt-how-to-switch-widgets-in-qstackedwidget # We can set up button functionality here instead. self.ui.toMainMenu.clicked.connect(self.refreshMenu) # then at either point regenerate the question by running the function # self.whatever.clicked.connect(self.newQuestion) self.ui.toMainMenu_2.clicked.connect(self.refreshMenu) self.ui.toMainMenu_3.clicked.connect(self.refreshMenu) self.ui.toSettings.clicked.connect(self.refreshSettings) self.ui.toQuestion.clicked.connect(self.newQuestion) self.ui.toQuestion_2.clicked.connect(self.deleteOldQuestion) self.ui.toAnswer.clicked.connect(lambda : self.ui.stackedWidget.setCurrentIndex(3)) self.ui.difficultybox.addItems(["Easy","Normal","Hard"]) topics=session.evaluate('''Keys[questionRepo["Easy"]]''') self.ui.topicbox.addItems(list(topics)) # to access difficulty do self.ui.difficultybox.currentText() # For when you exit a menu and a question has been generated, this will remove the previous question and answer. def refresh(self): if self.ui.verticalLayout_5.count() < 2: return else: if self.ui.verticalLayout.count() == 3: self.ui.verticalLayout.removeWidget(self.label1) self.label1.deleteLater() self.label1 = None qBox = self.ui.verticalLayout_5.itemAt(1) self.ui.verticalLayout_5.removeItem(qBox) self.ui.verticalLayout.removeWidget(self.canvasA) self.canvasA.deleteLater() self.canvasA = None def refreshSettings(self): self.ui.stackedWidget.setCurrentIndex(1) self.refresh() def refreshMenu(self): self.ui.stackedWidget.setCurrentIndex(0) self.refresh() def newQuestion(self): topic=self.ui.topicbox.currentText() difficulty=self.ui.difficultybox.currentText() chk = session.evaluate(wlexpr('''TopicLength["'''+str(topic)+'''","'''+str(difficulty)+'''"]''')) if chk == 0: return self.ui.stackedWidget.setCurrentIndex(2) # Go to question menu qa=session.evaluate(wlexpr('''evalQuestion["'''+str(topic)+'''","'''+str(difficulty)+'''"]''')) q =qa[0] a=qa[1] img = qa[2] self.questionDisplay = QtWidgets.QHBoxLayout() self.questionDisplay.setObjectName("questionDisplay") spaceLeft= QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.questionDisplay.addItem(spaceLeft) self.question = Figure(facecolor=self.cl,edgecolor=self.cl) self.canvasQ = FigureCanvas(self.question) self.questionDisplay.addWidget(self.canvasQ) self.question.suptitle(q, x=0.0, y=0.5, horizontalalignment='left', verticalalignment='bottom', fontsize=10, color=self.textcolor) self.canvasQ.draw() spaceRight = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.questionDisplay.addItem(spaceRight) self.ui.verticalLayout_5.addLayout(self.questionDisplay) self.answer = Figure(facecolor=self.cl,edgecolor=self.cl) self.canvasA = FigureCanvas(self.answer) self.ui.verticalLayout.addWidget(self.canvasA) self.answer.suptitle(a, x=0.0, y=0.6, horizontalalignment='left', verticalalignment='top', fontsize=10, color=self.textcolor) self.canvasA.draw() # Image handling, if there is a 0 that means there is no image, otherwise do: if img != 0: self.imageQuestion = True self.label1 = QtWidgets.QLabel(self) self.pixmap1 = QPixmap(img) self.label1.setPixmap(self.pixmap1) self.resize(self.pixmap1.width(), self.pixmap1.height()) self.ui.verticalLayout.addWidget(self.label1) self.show() else: self.imageQuestion = False # add bit with getting information from mathematica then setting all the required fields def deleteOldQuestion(self): qBox = self.ui.verticalLayout_5.itemAt(1) self.ui.verticalLayout_5.removeItem(qBox) self.ui.verticalLayout.removeWidget(self.canvasA) self.canvasA.deleteLater() self.canvasA = None if self.imageQuestion == True: self.ui.verticalLayout.removeWidget(self.label1) self.label1.deleteLater() self.label1 = None self.newQuestion()
def change_cursor(self, path): cursor_pixmap = QPixmap(path).scaled(32, 32) self.setCursor(QCursor(cursor_pixmap, 0, cursor_pixmap.height()))
class PixmapDial(QDial): # enum CustomPaintMode CUSTOM_PAINT_MODE_NULL = 0 # default (NOTE: only this mode has label gradient) CUSTOM_PAINT_MODE_CARLA_WET = 1 # color blue-green gradient (reserved #3) CUSTOM_PAINT_MODE_CARLA_VOL = 2 # color blue (reserved #3) CUSTOM_PAINT_MODE_CARLA_L = 3 # color yellow (reserved #4) CUSTOM_PAINT_MODE_CARLA_R = 4 # color yellow (reserved #4) CUSTOM_PAINT_MODE_CARLA_PAN = 5 # color yellow (reserved #3) CUSTOM_PAINT_MODE_COLOR = 6 # color, selectable (reserved #3) CUSTOM_PAINT_MODE_ZITA = 7 # custom zita knob (reserved #6) CUSTOM_PAINT_MODE_NO_GRADIENT = 8 # skip label gradient # enum Orientation HORIZONTAL = 0 VERTICAL = 1 HOVER_MIN = 0 HOVER_MAX = 9 MODE_DEFAULT = 0 MODE_LINEAR = 1 # signals realValueChanged = pyqtSignal(float) def __init__(self, parent, index=0): QDial.__init__(self, parent) self.fDialMode = self.MODE_LINEAR self.fMinimum = 0.0 self.fMaximum = 1.0 self.fRealValue = 0.0 self.fPrecision = 10000 self.fIsInteger = False self.fIsHovered = False self.fIsPressed = False self.fHoverStep = self.HOVER_MIN self.fLastDragPos = None self.fLastDragValue = 0.0 self.fIndex = index self.fPixmap = QPixmap(":/bitmaps/dial_01d.png") self.fPixmapNum = "01" if self.fPixmap.width() > self.fPixmap.height(): self.fPixmapOrientation = self.HORIZONTAL else: self.fPixmapOrientation = self.VERTICAL self.fLabel = "" self.fLabelPos = QPointF(0.0, 0.0) self.fLabelFont = QFont(self.font()) self.fLabelFont.setPixelSize(8) self.fLabelWidth = 0 self.fLabelHeight = 0 if self.palette().window().color().lightness() > 100: # Light background c = self.palette().dark().color() self.fLabelGradientColor1 = c self.fLabelGradientColor2 = QColor(c.red(), c.green(), c.blue(), 0) self.fLabelGradientColorT = [self.palette().buttonText().color(), self.palette().mid().color()] else: # Dark background self.fLabelGradientColor1 = QColor(0, 0, 0, 255) self.fLabelGradientColor2 = QColor(0, 0, 0, 0) self.fLabelGradientColorT = [Qt.white, Qt.darkGray] self.fLabelGradient = QLinearGradient(0, 0, 0, 1) self.fLabelGradient.setColorAt(0.0, self.fLabelGradientColor1) self.fLabelGradient.setColorAt(0.6, self.fLabelGradientColor1) self.fLabelGradient.setColorAt(1.0, self.fLabelGradientColor2) self.fLabelGradientRect = QRectF(0.0, 0.0, 0.0, 0.0) self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_NULL self.fCustomPaintColor = QColor(0xff, 0xff, 0xff) self.updateSizes() # Fake internal value, custom precision QDial.setMinimum(self, 0) QDial.setMaximum(self, self.fPrecision) QDial.setValue(self, 0) self.valueChanged.connect(self.slot_valueChanged) def getIndex(self): return self.fIndex def getBaseSize(self): return self.fPixmapBaseSize def forceWhiteLabelGradientText(self): self.fLabelGradientColor1 = QColor(0, 0, 0, 255) self.fLabelGradientColor2 = QColor(0, 0, 0, 0) self.fLabelGradientColorT = [Qt.white, Qt.darkGray] def setLabelColor(self, enabled, disabled): self.fLabelGradientColor1 = QColor(0, 0, 0, 255) self.fLabelGradientColor2 = QColor(0, 0, 0, 0) self.fLabelGradientColorT = [enabled, disabled] def updateSizes(self): self.fPixmapWidth = self.fPixmap.width() self.fPixmapHeight = self.fPixmap.height() if self.fPixmapWidth < 1: self.fPixmapWidth = 1 if self.fPixmapHeight < 1: self.fPixmapHeight = 1 if self.fPixmapOrientation == self.HORIZONTAL: self.fPixmapBaseSize = self.fPixmapHeight self.fPixmapLayersCount = self.fPixmapWidth / self.fPixmapHeight else: self.fPixmapBaseSize = self.fPixmapWidth self.fPixmapLayersCount = self.fPixmapHeight / self.fPixmapWidth self.setMinimumSize(self.fPixmapBaseSize, self.fPixmapBaseSize + self.fLabelHeight + 5) self.setMaximumSize(self.fPixmapBaseSize, self.fPixmapBaseSize + self.fLabelHeight + 5) if not self.fLabel: self.fLabelHeight = 0 self.fLabelWidth = 0 return self.fLabelWidth = QFontMetrics(self.fLabelFont).width(self.fLabel) self.fLabelHeight = QFontMetrics(self.fLabelFont).height() self.fLabelPos.setX(float(self.fPixmapBaseSize)/2.0 - float(self.fLabelWidth)/2.0) if self.fPixmapNum in ("01", "02", "07", "08", "09", "10"): self.fLabelPos.setY(self.fPixmapBaseSize + self.fLabelHeight) elif self.fPixmapNum in ("11",): self.fLabelPos.setY(self.fPixmapBaseSize + self.fLabelHeight*2/3) else: self.fLabelPos.setY(self.fPixmapBaseSize + self.fLabelHeight/2) self.fLabelGradient.setStart(0, float(self.fPixmapBaseSize)/2.0) self.fLabelGradient.setFinalStop(0, self.fPixmapBaseSize + self.fLabelHeight + 5) self.fLabelGradientRect = QRectF(float(self.fPixmapBaseSize)/8.0, float(self.fPixmapBaseSize)/2.0, float(self.fPixmapBaseSize*3)/4.0, self.fPixmapBaseSize+self.fLabelHeight+5) def setCustomPaintMode(self, paintMode): if self.fCustomPaintMode == paintMode: return self.fCustomPaintMode = paintMode self.update() def setCustomPaintColor(self, color): if self.fCustomPaintColor == color: return self.fCustomPaintColor = color self.update() def setLabel(self, label): if self.fLabel == label: return self.fLabel = label self.updateSizes() self.update() def setIndex(self, index): self.fIndex = index def setPixmap(self, pixmapId): self.fPixmapNum = "%02i" % pixmapId self.fPixmap.load(":/bitmaps/dial_%s%s.png" % (self.fPixmapNum, "" if self.isEnabled() else "d")) if self.fPixmap.width() > self.fPixmap.height(): self.fPixmapOrientation = self.HORIZONTAL else: self.fPixmapOrientation = self.VERTICAL # special pixmaps if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_NULL: # reserved for carla-wet, carla-vol, carla-pan and color if self.fPixmapNum == "03": self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_COLOR # reserved for carla-L and carla-R elif self.fPixmapNum == "04": self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_CARLA_L # reserved for zita elif self.fPixmapNum == "06": self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_ZITA self.updateSizes() self.update() def setPrecision(self, value, isInteger): self.fPrecision = value self.fIsInteger = isInteger QDial.setMaximum(self, value) def setMinimum(self, value): self.fMinimum = value def setMaximum(self, value): self.fMaximum = value def setValue(self, value, emitSignal=False): if self.fRealValue == value: return if value <= self.fMinimum: qtValue = 0 self.fRealValue = self.fMinimum elif value >= self.fMaximum: qtValue = self.fPrecision self.fRealValue = self.fMaximum else: qtValue = round(float(value - self.fMinimum) / float(self.fMaximum - self.fMinimum) * self.fPrecision) self.fRealValue = value # Block change signal, we'll handle it ourselves self.blockSignals(True) QDial.setValue(self, qtValue) self.blockSignals(False) if emitSignal: self.realValueChanged.emit(self.fRealValue) @pyqtSlot(int) def slot_valueChanged(self, value): self.fRealValue = float(value)/self.fPrecision * (self.fMaximum - self.fMinimum) + self.fMinimum self.realValueChanged.emit(self.fRealValue) @pyqtSlot() def slot_updatePixmap(self): self.setPixmap(int(self.fPixmapNum)) def minimumSizeHint(self): return QSize(self.fPixmapBaseSize, self.fPixmapBaseSize) def sizeHint(self): return QSize(self.fPixmapBaseSize, self.fPixmapBaseSize) def changeEvent(self, event): QDial.changeEvent(self, event) # Force pixmap update if enabled state changes if event.type() == QEvent.EnabledChange: self.setPixmap(int(self.fPixmapNum)) def enterEvent(self, event): self.fIsHovered = True if self.fHoverStep == self.HOVER_MIN: self.fHoverStep = self.HOVER_MIN + 1 QDial.enterEvent(self, event) def leaveEvent(self, event): self.fIsHovered = False if self.fHoverStep == self.HOVER_MAX: self.fHoverStep = self.HOVER_MAX - 1 QDial.leaveEvent(self, event) def mousePressEvent(self, event): if self.fDialMode == self.MODE_DEFAULT: return QDial.mousePressEvent(self, event) if event.button() == Qt.LeftButton: self.fIsPressed = True self.fLastDragPos = event.pos() self.fLastDragValue = self.fRealValue def mouseMoveEvent(self, event): if self.fDialMode == self.MODE_DEFAULT: return QDial.mouseMoveEvent(self, event) if not self.fIsPressed: return range = (self.fMaximum - self.fMinimum) / 4.0 pos = event.pos() dx = range * float(pos.x() - self.fLastDragPos.x()) / self.width() dy = range * float(pos.y() - self.fLastDragPos.y()) / self.height() value = self.fLastDragValue + dx - dy if value < self.fMinimum: value = self.fMinimum elif value > self.fMaximum: value = self.fMaximum elif self.fIsInteger: value = float(round(value)) self.setValue(value, True) def mouseReleaseEvent(self, event): if self.fDialMode == self.MODE_DEFAULT: return QDial.mouseReleaseEvent(self, event) if self.fIsPressed: self.fIsPressed = False def paintEvent(self, event): painter = QPainter(self) event.accept() painter.save() painter.setRenderHint(QPainter.Antialiasing, True) if self.fLabel: if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_NULL: painter.setPen(self.fLabelGradientColor2) painter.setBrush(self.fLabelGradient) painter.drawRect(self.fLabelGradientRect) painter.setFont(self.fLabelFont) painter.setPen(self.fLabelGradientColorT[0 if self.isEnabled() else 1]) painter.drawText(self.fLabelPos, self.fLabel) if self.isEnabled(): normValue = float(self.fRealValue - self.fMinimum) / float(self.fMaximum - self.fMinimum) target = QRectF(0.0, 0.0, self.fPixmapBaseSize, self.fPixmapBaseSize) curLayer = int((self.fPixmapLayersCount - 1) * normValue) if self.fPixmapOrientation == self.HORIZONTAL: xpos = self.fPixmapBaseSize * curLayer ypos = 0.0 else: xpos = 0.0 ypos = self.fPixmapBaseSize * curLayer source = QRectF(xpos, ypos, self.fPixmapBaseSize, self.fPixmapBaseSize) painter.drawPixmap(target, self.fPixmap, source) # Custom knobs (Dry/Wet and Volume) if self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_WET, self.CUSTOM_PAINT_MODE_CARLA_VOL): # knob color colorGreen = QColor(0x5D, 0xE7, 0x3D).lighter(100 + self.fHoverStep*6) colorBlue = QColor(0x3E, 0xB8, 0xBE).lighter(100 + self.fHoverStep*6) # draw small circle ballRect = QRectF(8.0, 8.0, 15.0, 15.0) ballPath = QPainterPath() ballPath.addEllipse(ballRect) #painter.drawRect(ballRect) tmpValue = (0.375 + 0.75*normValue) ballValue = tmpValue - floor(tmpValue) ballPoint = ballPath.pointAtPercent(ballValue) # draw arc startAngle = 216*16 spanAngle = -252*16*normValue if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_WET: painter.setBrush(colorBlue) painter.setPen(QPen(colorBlue, 0)) painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2)) gradient = QConicalGradient(15.5, 15.5, -45) gradient.setColorAt(0.0, colorBlue) gradient.setColorAt(0.125, colorBlue) gradient.setColorAt(0.625, colorGreen) gradient.setColorAt(0.75, colorGreen) gradient.setColorAt(0.76, colorGreen) gradient.setColorAt(1.0, colorGreen) painter.setBrush(gradient) painter.setPen(QPen(gradient, 3)) else: painter.setBrush(colorBlue) painter.setPen(QPen(colorBlue, 0)) painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2)) painter.setBrush(colorBlue) painter.setPen(QPen(colorBlue, 3)) painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle) # Custom knobs (L and R) elif self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_L, self.CUSTOM_PAINT_MODE_CARLA_R): # knob color color = QColor(0xAD, 0xD5, 0x48).lighter(100 + self.fHoverStep*6) # draw small circle ballRect = QRectF(7.0, 8.0, 11.0, 12.0) ballPath = QPainterPath() ballPath.addEllipse(ballRect) #painter.drawRect(ballRect) tmpValue = (0.375 + 0.75*normValue) ballValue = tmpValue - floor(tmpValue) ballPoint = ballPath.pointAtPercent(ballValue) painter.setBrush(color) painter.setPen(QPen(color, 0)) painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.0, 2.0)) # draw arc if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_L: startAngle = 216*16 spanAngle = -252.0*16*normValue else: startAngle = 324.0*16 spanAngle = 252.0*16*(1.0-normValue) painter.setPen(QPen(color, 2)) painter.drawArc(3.5, 4.5, 22.0, 22.0, startAngle, spanAngle) # Custom knobs (Color) elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_COLOR: # knob color color = self.fCustomPaintColor.lighter(100 + self.fHoverStep*6) # draw small circle ballRect = QRectF(8.0, 8.0, 15.0, 15.0) ballPath = QPainterPath() ballPath.addEllipse(ballRect) tmpValue = (0.375 + 0.75*normValue) ballValue = tmpValue - floor(tmpValue) ballPoint = ballPath.pointAtPercent(ballValue) # draw arc startAngle = 216*16 spanAngle = -252*16*normValue painter.setBrush(color) painter.setPen(QPen(color, 0)) painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2)) painter.setBrush(color) painter.setPen(QPen(color, 3)) painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle) # Custom knobs (Zita) elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_ZITA: a = normValue * pi * 1.5 - 2.35 r = 10.0 x = 10.5 y = 10.5 x += r * sin(a) y -= r * cos(a) painter.setBrush(Qt.black) painter.setPen(QPen(Qt.black, 2)) painter.drawLine(QPointF(11.0, 11.0), QPointF(x, y)) # Custom knobs else: painter.restore() return if self.HOVER_MIN < self.fHoverStep < self.HOVER_MAX: self.fHoverStep += 1 if self.fIsHovered else -1 QTimer.singleShot(20, self.update) else: # isEnabled() target = QRectF(0.0, 0.0, self.fPixmapBaseSize, self.fPixmapBaseSize) painter.drawPixmap(target, self.fPixmap, target) painter.restore() def resizeEvent(self, event): QDial.resizeEvent(self, event) self.updateSizes()
def adding_image_to_lbl(self , aarray): mostafa = qimage2ndarray.array2qimage(aarray) mostafa.save("output.jpg") pixmap = QPixmap("output.jpg") pixmap = pixmap.scaled(int(pixmap.height()), int(pixmap.width()), QtCore.Qt.KeepAspectRatio) return pixmap
class SnapWidget(QWidget, Ui_SnapWidget): """ Class implementing the snapshot widget. """ ModeFullscreen = 0 ModeScreen = 1 ModeRectangle = 2 ModeFreehand = 3 ModeEllipse = 4 def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(SnapWidget, self).__init__(parent) self.setupUi(self) self.saveButton.setIcon(UI.PixmapCache.getIcon("fileSaveAs.png")) self.takeButton.setIcon(UI.PixmapCache.getIcon("cameraPhoto.png")) self.copyButton.setIcon(UI.PixmapCache.getIcon("editCopy.png")) self.copyPreviewButton.setIcon(UI.PixmapCache.getIcon("editCopy.png")) self.setWindowIcon(UI.PixmapCache.getIcon("ericSnap.png")) self.modeCombo.addItem(self.tr("Fullscreen"), SnapWidget.ModeFullscreen) self.modeCombo.addItem(self.tr("Rectangular Selection"), SnapWidget.ModeRectangle) self.modeCombo.addItem(self.tr("Ellipical Selection"), SnapWidget.ModeEllipse) self.modeCombo.addItem(self.tr("Freehand Selection"), SnapWidget.ModeFreehand) if QApplication.desktop().screenCount() > 1: self.modeCombo.addItem(self.tr("Current Screen"), SnapWidget.ModeScreen) self.__mode = int(Preferences.Prefs.settings.value("Snapshot/Mode", 0)) index = self.modeCombo.findData(self.__mode) if index == -1: index = 0 self.modeCombo.setCurrentIndex(index) self.__delay = int( Preferences.Prefs.settings.value("Snapshot/Delay", 0)) self.delaySpin.setValue(self.__delay) if PYQT_VERSION_STR >= "5.0.0": from PyQt5.QtCore import QStandardPaths picturesLocation = QStandardPaths.writableLocation( QStandardPaths.PicturesLocation) else: from PyQt5.QtGui import QDesktopServices picturesLocation = QDesktopServices.storageLocation( QDesktopServices.PicturesLocation) self.__filename = Preferences.Prefs.settings.value( "Snapshot/Filename", os.path.join(picturesLocation, self.tr("snapshot") + "1.png")) self.__grabber = None self.__snapshot = QPixmap() self.__savedPosition = QPoint() self.__modified = False self.__locale = QLocale() self.__grabberWidget = QWidget(None, Qt.X11BypassWindowManagerHint) self.__grabberWidget.move(-10000, -10000) self.__grabberWidget.installEventFilter(self) self.__initFileFilters() self.__initShortcuts() self.preview.startDrag.connect(self.__dragSnapshot) from .SnapshotTimer import SnapshotTimer self.__grabTimer = SnapshotTimer() self.__grabTimer.timeout.connect(self.__grabTimerTimeout) self.__updateTimer = QTimer() self.__updateTimer.setSingleShot(True) self.__updateTimer.timeout.connect(self.__updatePreview) self.__updateCaption() self.takeButton.setFocus() def __initFileFilters(self): """ Private method to define the supported image file filters. """ filters = { 'bmp': self.tr("Windows Bitmap File (*.bmp)"), 'gif': self.tr("Graphic Interchange Format File (*.gif)"), 'ico': self.tr("Windows Icon File (*.ico)"), 'jpg': self.tr("JPEG File (*.jpg)"), 'mng': self.tr("Multiple-Image Network Graphics File (*.mng)"), 'pbm': self.tr("Portable Bitmap File (*.pbm)"), 'pcx': self.tr("Paintbrush Bitmap File (*.pcx)"), 'pgm': self.tr("Portable Graymap File (*.pgm)"), 'png': self.tr("Portable Network Graphics File (*.png)"), 'ppm': self.tr("Portable Pixmap File (*.ppm)"), 'sgi': self.tr("Silicon Graphics Image File (*.sgi)"), 'svg': self.tr("Scalable Vector Graphics File (*.svg)"), 'tga': self.tr("Targa Graphic File (*.tga)"), 'tif': self.tr("TIFF File (*.tif)"), 'xbm': self.tr("X11 Bitmap File (*.xbm)"), 'xpm': self.tr("X11 Pixmap File (*.xpm)"), } outputFormats = [] writeFormats = QImageWriter.supportedImageFormats() for writeFormat in writeFormats: try: outputFormats.append(filters[bytes(writeFormat).decode()]) except KeyError: pass outputFormats.sort() self.__outputFilter = ';;'.join(outputFormats) self.__defaultFilter = filters['png'] def __initShortcuts(self): """ Private method to initialize the keyboard shortcuts. """ self.__quitShortcut = QShortcut( QKeySequence(QKeySequence.Quit), self, self.close) self.__copyShortcut = QShortcut( QKeySequence(QKeySequence.Copy), self, self.copyButton.animateClick) self.__quickSaveShortcut = QShortcut( QKeySequence(Qt.Key_Q), self, self.__quickSave) self.__save1Shortcut = QShortcut( QKeySequence(QKeySequence.Save), self, self.saveButton.animateClick) self.__save2Shortcut = QShortcut( QKeySequence(Qt.Key_S), self, self.saveButton.animateClick) self.__grab1Shortcut = QShortcut( QKeySequence(QKeySequence.New), self, self.takeButton.animateClick) self.__grab2Shortcut = QShortcut( QKeySequence(Qt.Key_N), self, self.takeButton.animateClick) self.__grab3Shortcut = QShortcut( QKeySequence(Qt.Key_Space), self, self.takeButton.animateClick) def __quickSave(self): """ Private slot to save the snapshot bypassing the file selection dialog. """ if not self.__snapshot.isNull(): while os.path.exists(self.__filename): self.__autoIncFilename() if self.__saveImage(self.__filename): self.__modified = False self.__autoIncFilename() self.__updateCaption() @pyqtSlot() def on_saveButton_clicked(self): """ Private slot to save the snapshot. """ if not self.__snapshot.isNull(): while os.path.exists(self.__filename): self.__autoIncFilename() fileName, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Snapshot"), self.__filename, self.__outputFilter, self.__defaultFilter, E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if not fileName: return ext = QFileInfo(fileName).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fileName += ex if self.__saveImage(fileName): self.__modified = False self.__filename = fileName self.__autoIncFilename() self.__updateCaption() def __saveImage(self, fileName): """ Private method to save the snapshot. @param fileName name of the file to save to (string) @return flag indicating success (boolean) """ if QFileInfo(fileName).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Snapshot"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fileName), icon=E5MessageBox.Warning) if not res: return False file = QFile(fileName) if not file.open(QFile.WriteOnly): E5MessageBox.warning( self, self.tr("Save Snapshot"), self.tr("Cannot write file '{0}:\n{1}.") .format(fileName, file.errorString())) return False ok = self.__snapshot.save(file) file.close() if not ok: E5MessageBox.warning( self, self.tr("Save Snapshot"), self.tr("Cannot write file '{0}:\n{1}.") .format(fileName, file.errorString())) return ok def __autoIncFilename(self): """ Private method to auto-increment the file name. """ # Extract the file name name = os.path.basename(self.__filename) # If the name contains a number, then increment it. numSearch = QRegExp("(^|[^\\d])(\\d+)") # We want to match as far left as possible, and when the number is # at the start of the name. # Does it have a number? start = numSearch.lastIndexIn(name) if start != -1: # It has a number, increment it. start = numSearch.pos(2) # Only the second group is of interest. numAsStr = numSearch.capturedTexts()[2] number = "{0:0{width}d}".format( int(numAsStr) + 1, width=len(numAsStr)) name = name[:start] + number + name[start + len(numAsStr):] else: # no number start = name.rfind('.') if start != -1: # has a '.' somewhere, e.g. it has an extension name = name[:start] + '1' + name[start:] else: # no extension, just tack it on to the end name += '1' self.__filename = os.path.join(os.path.dirname(self.__filename), name) self.__updateCaption() @pyqtSlot() def on_takeButton_clicked(self): """ Private slot to take a snapshot. """ self.__mode = self.modeCombo.itemData(self.modeCombo.currentIndex()) self.__delay = self.delaySpin.value() self.__savedPosition = self.pos() self.hide() if self.__delay: self.__grabTimer.start(self.__delay) else: QTimer.singleShot(200, self.__startUndelayedGrab) def __grabTimerTimeout(self): """ Private slot to perform a delayed grab operation. """ if self.__mode == SnapWidget.ModeRectangle: self.__grabRectangle() elif self.__mode == SnapWidget.ModeEllipse: self.__grabEllipse() elif self.__mode == SnapWidget.ModeFreehand: self.__grabFreehand() else: self.__performGrab() def __startUndelayedGrab(self): """ Private slot to perform an undelayed grab operation. """ if self.__mode == SnapWidget.ModeRectangle: self.__grabRectangle() elif self.__mode == SnapWidget.ModeEllipse: self.__grabEllipse() elif self.__mode == SnapWidget.ModeFreehand: self.__grabFreehand() else: if Globals.isMacPlatform(): self.__performGrab() else: self.__grabberWidget.show() self.__grabberWidget.grabMouse(Qt.CrossCursor) def __grabRectangle(self): """ Private method to grab a rectangular screen region. """ from .SnapshotRegionGrabber import SnapshotRegionGrabber self.__grabber = SnapshotRegionGrabber( mode=SnapshotRegionGrabber.Rectangle) self.__grabber.grabbed.connect(self.__captured) def __grabEllipse(self): """ Private method to grab an elliptical screen region. """ from .SnapshotRegionGrabber import SnapshotRegionGrabber self.__grabber = SnapshotRegionGrabber( mode=SnapshotRegionGrabber.Ellipse) self.__grabber.grabbed.connect(self.__captured) def __grabFreehand(self): """ Private method to grab a non-rectangular screen region. """ from .SnapshotFreehandGrabber import SnapshotFreehandGrabber self.__grabber = SnapshotFreehandGrabber() self.__grabber.grabbed.connect(self.__captured) def __performGrab(self): """ Private method to perform a screen grab other than a selected region. """ self.__grabberWidget.releaseMouse() self.__grabberWidget.hide() self.__grabTimer.stop() if self.__mode == SnapWidget.ModeFullscreen: desktop = QApplication.desktop() if qVersion() >= "5.0.0": self.__snapshot = QApplication.screens()[0].grabWindow( desktop.winId(), desktop.x(), desktop.y(), desktop.width(), desktop.height()) else: self.__snapshot = QPixmap.grabWindow( desktop.winId(), desktop.x(), desktop.y(), desktop.width(), desktop.height()) elif self.__mode == SnapWidget.ModeScreen: desktop = QApplication.desktop() screenId = desktop.screenNumber(QCursor.pos()) geom = desktop.screenGeometry(screenId) x = geom.x() y = geom.y() if qVersion() >= "5.0.0": self.__snapshot = QApplication.screens()[0].grabWindow( desktop.winId(), x, y, geom.width(), geom.height()) else: self.__snapshot = QPixmap.grabWindow( desktop.winId(), x, y, geom.width(), geom.height()) else: self.__snapshot = QPixmap() self.__redisplay() self.__modified = True self.__updateCaption() def __redisplay(self): """ Private method to redisplay the window. """ self.__updatePreview() QApplication.restoreOverrideCursor() if not self.__savedPosition.isNull(): self.move(self.__savedPosition) self.show() self.raise_() self.saveButton.setEnabled(not self.__snapshot.isNull()) self.copyButton.setEnabled(not self.__snapshot.isNull()) self.copyPreviewButton.setEnabled(not self.__snapshot.isNull()) @pyqtSlot() def on_copyButton_clicked(self): """ Private slot to copy the snapshot to the clipboard. """ if not self.__snapshot.isNull(): QApplication.clipboard().setPixmap(QPixmap(self.__snapshot)) @pyqtSlot() def on_copyPreviewButton_clicked(self): """ Private slot to copy the snapshot preview to the clipboard. """ QApplication.clipboard().setPixmap(self.preview.pixmap()) def __captured(self, pixmap): """ Private slot to show a preview of the snapshot. @param pixmap pixmap of the snapshot (QPixmap) """ self.__grabber.close() self.__snapshot = QPixmap(pixmap) self.__grabber.grabbed.disconnect(self.__captured) self.__grabber = None self.__redisplay() self.__modified = True self.__updateCaption() def __updatePreview(self): """ Private slot to update the preview picture. """ self.preview.setToolTip(self.tr( "Preview of the snapshot image ({0} x {1})").format( self.__locale.toString(self.__snapshot.width()), self.__locale.toString(self.__snapshot.height())) ) self.preview.setPreview(self.__snapshot) self.preview.adjustSize() def resizeEvent(self, evt): """ Protected method handling a resizing of the window. @param evt resize event (QResizeEvent) """ self.__updateTimer.start(200) def __dragSnapshot(self): """ Private slot handling the dragging of the preview picture. """ drag = QDrag(self) mimeData = QMimeData() mimeData.setImageData(self.__snapshot) drag.setMimeData(mimeData) drag.setPixmap(self.preview.pixmap()) drag.exec_(Qt.CopyAction) def eventFilter(self, obj, evt): """ Public method to handle event for other objects. @param obj reference to the object (QObject) @param evt reference to the event (QEvent) @return flag indicating that the event should be filtered out (boolean) """ if obj == self.__grabberWidget and \ evt.type() == QEvent.MouseButtonPress: if QWidget.mouseGrabber() != self.__grabberWidget: return False if evt.button() == Qt.LeftButton: self.__performGrab() return False def closeEvent(self, evt): """ Protected method handling the close event. @param evt close event (QCloseEvent) """ if self.__modified: res = E5MessageBox.question( self, self.tr("eric6 Snapshot"), self.tr( """The application contains an unsaved snapshot."""), E5MessageBox.StandardButtons( E5MessageBox.Abort | E5MessageBox.Discard | E5MessageBox.Save)) if res == E5MessageBox.Abort: evt.ignore() return elif res == E5MessageBox.Save: self.on_saveButton_clicked() Preferences.Prefs.settings.setValue( "Snapshot/Delay", self.delaySpin.value()) Preferences.Prefs.settings.setValue( "Snapshot/Mode", self.modeCombo.itemData(self.modeCombo.currentIndex())) Preferences.Prefs.settings.setValue( "Snapshot/Filename", self.__filename) Preferences.Prefs.settings.sync() def __updateCaption(self): """ Private method to update the window caption. """ self.setWindowTitle("{0}[*] - {1}".format( os.path.basename(self.__filename), self.tr("eric6 Snapshot"))) self.setWindowModified(self.__modified) self.pathNameEdit.setText(os.path.dirname(self.__filename))
class QtVideoMockup(AbstractVideoDevice): def __init__(self, name): AbstractVideoDevice.__init__(self, name) self.force_update = None self.image_type = None self.image = None def init(self): current_path = os.path.dirname(os.path.abspath(__file__)).split(os.sep) current_path = os.path.join(*current_path[1:-2]) default_image_path = "/" + current_path + "/test/fakeimg.jpg" image_path = self.getProperty("file_name", default_image_path) self.image = QPixmap(image_path) self.image_dimensions = (self.image.width(), self.image.height()) self.painter = QPainter(self.image) custom_pen = QPen(Qt.SolidLine) custom_pen.setColor(Qt.black) custom_pen.setWidth(1) self.painter.setPen(custom_pen) custom_brush = QBrush(Qt.SolidPattern) custom_brush.setColor(Qt.lightGray) self.painter.setBrush(custom_brush) self.setIsReady(True) AbstractVideoDevice.init(self) def get_new_image(self): self.painter.drawRect(self.image.width() - 75, self.image.height() - 30, 70, 20) self.painter.drawText( self.image.width() - 70, self.image.height() - 15, time.strftime("%H:%M:%S") ) self.emit("imageReceived", self.image) def save_snapshot(self, filename, image_type="PNG"): qimage = QImage(self.image) qimage.save(filename, image_type) def get_snapshot(self, bw=None, return_as_array=None): qimage = QImage(self.image) if return_as_array: qimage = qimage.convertToFormat(4) ptr = qimage.bits() ptr.setsize(qimage.byteCount()) image_array = np.array(ptr).reshape(qimage.height(), qimage.width(), 4) if bw: return np.dot(image_array[..., :3], [0.299, 0.587, 0.144]) else: return image_array else: if bw: return qimage.convertToFormat(QImage.Format_Mono) else: return qimage def get_contrast(self): return 34 def set_contrast(self, contrast_value): return def get_brightness(self): return 54 def set_brightness(self, brightness_value): return def get_gain(self): return 32 def set_gain(self, gain_value): return def get_gamma(self): return 22 def set_gamma(self, gamma_value): return def get_exposure_time(self): return 0.23 def get_video_live(self): return True def get_raw_image_size(self): return list(self.image_dimensions)
class MyWidget(QWidget): def __init__(self, parent): super().__init__(parent) self.initUI() def initUI(self): self.setMinimumSize(1, 30) self.setFocusPolicy(Qt.StrongFocus) # to be able to accept key events self.paint_image = QPixmap(self.width(), self.height()) self.background_color = QColor(70, 70, 70) self.fps = 30 self.timer = QTimer() self.timer.timeout.connect(self.nextFrame) self.timer.start(1000 / 30) self.frame_count = 0 self.x1 = 50 self.y1 = 50 self.radius1 = 50 self.color2 = QColor(0, 0, 255) self.x2 = 50 self.y2 = 50 self.angle2 = 20 def setFrameRate(self, fps): self.fps = fps if self.fps > 0: if not self.timer.isActive(): self.timer.start() self.timer.setInterval(1000 / self.fps) else: self.timer.stop() def nextFrame(self): mouse_pos = self.mapFromGlobal(QCursor.pos()) mouse_x = mouse_pos.x() mouse_y = mouse_pos.y() self.x1 = mouse_x self.y1 = mouse_y self.radius1 = self.radius1 + math.sin(self.frame_count / 8) * 4 delay = 20 self.x2 += (mouse_x - self.x2) / delay self.y2 += (mouse_y - self.y2) / delay self.frame_count += 1 if self.paint_image.width() != self.width() or self.paint_image.height() != self.height(): self.paint_image = QPixmap(self.width(), self.height()) self.paint_image.fill(self.background_color) p = QPainter() p.begin(self.paint_image) # auf das paint_image malen p.setBackground(self.background_color) # color when stuff is erased # Hintergrund löschen, wenn Rechteck bei der Maus angekommen ist # print("{0}, {1}".format(self.x2, mouse_x)) if round(self.x2) == mouse_x and round(self.y2) == mouse_y: p.eraseRect(0, 0, self.paint_image.width(), self.paint_image.height()) self.drawFrame(p) p.end() self.repaint() def drawFrame(self, p): pen = QPen(QColor(20, 20, 20), 10, Qt.SolidLine) p.setPen(pen) x1 = self.x1 - self.radius1 / 2 y1 = self.y1 - self.radius1 / 2 p.drawEllipse(x1, y1, self.radius1, self.radius1) pen = QPen(self.color2, 5, Qt.SolidLine) # blau p.setPen(pen) w2 = 50 # see https://www.khanacademy.org/computing/computer-programming/programming-games-visualizations/programming-transformations/a/rotation p.save() p.translate(self.x2, self.y2) p.rotate(self.angle2) # todo keypress p.drawRect(0, 0, w2, w2) p.restore() def paintEvent(self, e): p = QPainter() p.begin(self) # self.drawFrame(p) # Frame direkt malen (ohne paint_image) p.drawPixmap(0, 0, self.paint_image) p.end() def keyPressEvent(self, e): print(e.key(), e.text()) if e.key() == Qt.Key_Left: self.angle2 -= 10 elif e.key() == Qt.Key_Right: self.angle2 += 10 if e.key() == Qt.Key_P: print("P pressed") if e.key() == Qt.Key_C: print("C pressed") if self.color2 == QColor(0, 0, 255): self.color2 = QColor(0, 255, 0) else: self.color2 = QColor(0, 0, 255) def mousePressEvent(self, e): print(e.x(), e.y()) p = QPainter() p.begin(self.paint_image) # auf das paint_image malen self.drawOnClick(e, p) p.end() self.repaint() def drawOnClick(self, e, p): pen = QPen(QColor(255, 0, 0), 20, Qt.SolidLine, Qt.RoundCap) p.setPen(pen) p.drawPoint(e.x(), e.y())