Exemplo n.º 1
0
    def open_file(self):
        """
        Open image file for editing, scaling the smaller dimension and cropping the remainder.
        :return:
        """
        path, _ = QFileDialog.getOpenFileName(
            self, "Open file", "",
            "PNG image files (*.png); JPEG image files (*jpg); All files (*.*)"
        )

        if path:
            pixmap = QPixmap()
            pixmap.load(path)

            # We need to crop down to the size of our canvas. Get the size of the loaded image.
            iw = pixmap.width()
            ih = pixmap.height()

            # Get the size of the space we're filling.
            cw, ch = CANVAS_DIMENSIONS

            if iw / cw < ih / ch:  # The height is relatively bigger than the width.
                pixmap = pixmap.scaledToWidth(cw)
                hoff = (pixmap.height() - ch) // 2
                pixmap = pixmap.copy(
                    QRect(QPoint(0, hoff), QPoint(cw,
                                                  pixmap.height() - hoff)))

            elif iw / cw > ih / ch:  # The height is relatively bigger than the width.
                pixmap = pixmap.scaledToHeight(ch)
                woff = (pixmap.width() - cw) // 2
                pixmap = pixmap.copy(
                    QRect(QPoint(woff, 0), QPoint(pixmap.width() - woff, ch)))
            self.imagefilePath = path  # for the opened sketch files
            self.ui.Canvas.setPixmap(pixmap)
Exemplo n.º 2
0
    def open_file(self):
        path, _ = QFileDialog.getOpenFileName(
            self, "Open file", "",
            "PNG image files (*.png); JPEG image files (*jpg); All files (*.*)"
        )

        if path:
            pixmap = QPixmap()
            pixmap.load(path)

            iw = pixmap.width()
            ih = pixmap.height()
            cw, ch = CANVAS_DIMENSIONS

            if iw / cw < ih / ch:
                pixmap = pixmap.scaledToWidth(cw)
                hoff = (pixmap.height() - ch) // 2
                pixmap = pixmap.copy(
                    QRect(QPoint(0, hoff), QPoint(cw,
                                                  pixmap.height() - hoff)))

            elif iw / cw > ih / ch:
                pixmap = pixmap.scaledToHeight(ch)
                woff = (pixmap.width() - cw) // 2
                pixmap = pixmap.copy(
                    QRect(QPoint(woff, 0), QPoint(pixmap.width() - woff, ch)))

            self.canvas.setPixmap(pixmap)
Exemplo n.º 3
0
class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.origin_pixmap = QPixmap("apple.jpg")
        self.init_ui()

    def init_ui(self):
        self.setMinimumWidth(320)
        self.setMinimumHeight(240)
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        self.setLayout(layout)

        lb_1 = Label()

        self.origin_pixmap = self.origin_pixmap.scaledToHeight(240)  # 사이즈가 조정
        lb_1.setPixmap(self.origin_pixmap)
        layout.addWidget(lb_1)

        # 자를 영역 선택, 복사
        rect = QRect(50, 50, 50, 50)
        cropped = self.origin_pixmap.copy(rect)

        self.lb_2 = QLabel()
        self.lb_2.setPixmap(cropped)
        self.lb_2.setFixedSize(100, 100)
        layout.addWidget(self.lb_2)

        lb_1.selection_changed.connect(self.crop_image)

    @pyqtSlot(QRect, name="cropImage")
    def crop_image(self, crop_rect):
        # 자를 영역 선택, 복사
        cropped = self.origin_pixmap.copy(crop_rect)
        self.lb_2.setPixmap(cropped)
Exemplo n.º 4
0
    def __init__(self):
        #Program icon
        self.progIcon = QPixmap("img/icon175x175.png")
        #Flags
        _img = QPixmap("img/flags.png")
        self.flag = [
            QPixmap(_img.copy(37 * (i % 10), 22 * (i // 10), 36, 22))
            for i in range(80)
        ]
        #buffer the flags - used for showing them in system tooltips
        buffer = [QBuffer() for i in range(80)]
        for img, buf in zip(self.flag, buffer):
            buf.open(QIODevice.WriteOnly)
            img.scaledToHeight(12).save(buf, "PNG", quality=100)
        self.flagToolTip = [
            bytes(i.data().toBase64()).decode() for i in buffer
        ]
        self.emptyFlag = QPixmap(36, 22)
        self.emptyFlag.fill(QColor(255, 255, 255, 255))

        # Action icons
        _img = QPixmap("img/icons.png")
        self.icon = [
            QIcon(_img.copy(65 * (i % 10), 65 * (i // 10), 64, 64))
            for i in range(30)
        ]

        # Advisors
        self.advisor = [
            QPixmap("img/adv" + str(i + 1) + ".png") for i in range(4)
        ]
Exemplo n.º 5
0
class ProtoObj(object):
    def __init__(self, posX=0, posY=0, radX=30, radY=30, parent=None):
        super().__init__()
        self.posX = posX
        self.posY = posY
        self.radX = radX
        self.radY = radY
        self.parent = parent
        self.ellipse = QGraphicsEllipseItem(posX, posY, radX, radY)
        self.sheet = QPixmap('linkEdit.png')
        self.stand = []
        self.step = 0
        self.state = 0
        self.animation_timer = QTimer()
        self.animation_timer.timeout.connect(self.animate)
        self.animation_timer.setInterval(1000)
        self.animation_timer.start()

    def initObj(self):
        self.ellipse.setPos(self.posX, self.posY)
        self.ellipse.setPen(QPen(Qt.transparent, 1))
        self.ellipse.setBrush(QBrush(Qt.darkGreen))
        self.ellipse.setZValue(0)
        self.ellipse.setOpacity(1)
        effect = QGraphicsDropShadowEffect(self.parent)
        effect.setBlurRadius(15)
        effect.setColor(Qt.black)
        self.ellipse.setGraphicsEffect(effect)
        self.stand.append(self.sheet.copy(10, 15, 100, 120))
        self.stand.append(self.sheet.copy(130, 15, 100, 120))
        self.stand.append(self.sheet.copy(250, 15, 100, 120))
        self.pix = self.parent.m_scene.addPixmap(self.stand[0])
        self.pix.setPos(self.posX, self.posY)
        self.pix.setOffset(-20, -56)
        self.pix.setZValue(2)
        self.pix.setScale(1)

    def getObj(self):
        return [self.ellipse]

    def moveObj(self, velX, velY):
        self.posX += velX
        self.posY += velY
        self.pix.setPos(self.posX, self.posY)

    def animate(self):
        if self.state == 0:
            self.step += 1
            if self.step > 2:
                self.step = 0
            'standing'
            #self.pix = self.parent.m_scene.addPixmap(self.stand[self.step])
            self.pix.setPixmap(self.stand[self.step])
            self.pix.setPos(self.posX, self.posY)
            #self.pix.setOffset(-20, -70)
            self.pix.setZValue(2)
Exemplo n.º 6
0
class ScreenInfoManager:
    def __init__(self):
        self._screenNum = QApplication.desktop().screenCount()
        self._screenPos = QApplication.desktop().pos()
        self._screenSize = QApplication.desktop().size()
        self._captureRegion = QRect()
        self._drawRegion = QRect()
        self._screenImg = QPixmap()

    def refreshScrInfo(self):
        self._screenNum = QApplication.desktop().screenCount()
        self._screenPos = QApplication.desktop().pos()
        self._screenSize = QApplication.desktop().size()

    def screenshot(self):
        self._screenImg = QPixmap(self._screenSize)
        self._screenImg.fill(Qt.black)
        painter = QPainter(self._screenImg)
        for index, screen in enumerate(QApplication.screens()):
            p = screen.grabWindow(0)
            offx = QApplication.desktop().pos().x()
            offy = QApplication.desktop().pos().y()
            x, y, w, h = screen.geometry().getRect()
            painter.drawPixmap(QPoint(x - offx, y - offy), p)

    def get_captureRegionImg(self) -> QPixmap:
        return self._screenImg.copy(self._captureRegion)

    def get_drawRegionImg(self) -> QPixmap:
        return self._screenImg.copy(self._drawRegion)

    @property
    def screenImg(self):
        return self._screenImg

    @property
    def captureRegion(self):
        return self._captureRegion

    @captureRegion.setter
    def captureRegion(self, new_captureRegion):
        self._captureRegion = new_captureRegion

    @property
    def drawRegion(self):
        return self._drawRegion

    @drawRegion.setter
    def drawRegion(self, new_drawRegion):
        self._drawRegion = new_drawRegion
Exemplo n.º 7
0
    def drawResultBox(self):
        res = QPixmap.copy(self.pixmapOriginal)
        painter = QPainter(res)
        font = QFont('mono', 30, 1)
        painter.setFont(font)
        painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
        i = 0
        for box in self.results:

            lx, ly, rx, ry = box[:4]
            #painter.drawRect(lx, ly, rx-lx, ry-ly)
            p1_x = vector_result[i]
            p1_y = vector_result[i + 1]
            p2_x = vector_result[i + 2]
            p2_y = vector_result[i + 3]
            new_x1 = vector_result[i + 4]
            new_y1 = vector_result[i + 5]
            new_x2 = vector_result[i + 6]
            new_y2 = vector_result[i + 7]
            i = i + 8
            painter.drawLine(p1_x, p1_y, new_x1, new_y1)
            painter.drawLine(new_x1, new_y1, p2_x, p2_y)
            painter.drawLine(p1_x, p1_y, new_x2, new_y2)
            painter.drawLine(new_x2, new_y2, p2_x, p2_y)

            if len(box) == 5:
                painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
                painter.drawText(lx, ly + 15, self.key_config[box[-1]])
                painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))

        return res
Exemplo n.º 8
0
    def chooseImage(self):
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            None, "Choose Image", "",
            "Image Files (*.png *.jpg *.jpeg *.bmp *.gif)")

        if filename:
            predicted_im = self.predictor.predict(filename)
            predicted_im = Image.fromarray(
                (predicted_im * 255).astype(np.uint8))
            predicted_im = np.array(predicted_im)

            original_im = QPixmap(filename)
            original_im = original_im.scaled(self.size, self.size,
                                             QtCore.Qt.KeepAspectRatio)
            self.originalImage.setPixmap(original_im)

            grayscale_im = original_im.copy()
            grayscale_im = QtGui.QPixmap.toImage(grayscale_im)
            grayscale_im = grayscale_im.convertToFormat(
                QImage.Format_Grayscale8)
            self.grayscaleImage.setPixmap(
                QtGui.QPixmap.fromImage(grayscale_im))

            height, width, channel = predicted_im.shape
            bytesPerLine = 3 * width
            predicted_im = QImage(predicted_im.data, width, height,
                                  bytesPerLine, QImage.Format_RGB888)
            self.predictedImage.setPixmap(
                QtGui.QPixmap.fromImage(predicted_im))
Exemplo n.º 9
0
    def mouseMoveEvent(self, event):
        self.parent.cursorPos.setText('({}, {})'.format(
            event.pos().x(),
            event.pos().y()))
        if event.buttons() and Qt.LeftButton and self.drawing:
            self.pixmap = QPixmap.copy(self.prev_pixmap)
            painter = QPainter(self.pixmap)
            painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
            p1_x, p1_y = self.lastPoint.x(), self.lastPoint.y()
            p2_x, p2_y = event.pos().x(), event.pos().y()
            detx = p2_x - p1_x
            dety = p2_y - p1_y
            new_x1 = p1_x + (cmath.cos(cmath.pi / 4) * detx +
                             cmath.sin(cmath.pi / 4) * dety) / cmath.sqrt(2)
            new_y1 = p1_y + (cmath.cos(cmath.pi / 4) * dety -
                             cmath.sin(cmath.pi / 4) * detx) / cmath.sqrt(2)
            new_x2 = p1_x + (cmath.cos(-cmath.pi / 4) * detx +
                             cmath.sin(-cmath.pi / 4) * dety) / cmath.sqrt(2)
            new_y2 = p1_y + (-cmath.sin(-cmath.pi / 4) * detx +
                             cmath.cos(-cmath.pi / 4) * dety) / cmath.sqrt(2)

            new_x1, new_y1 = int(new_x1.real), int(new_y1.real)
            new_x2, new_y2 = int(new_x2.real), int(new_y2.real)

            painter.drawLine(p1_x, p1_y, new_x1, new_y1)
            painter.drawLine(new_x1, new_y1, p2_x, p2_y)
            painter.drawLine(p1_x, p1_y, new_x2, new_y2)
            painter.drawLine(new_x2, new_y2, p2_x, p2_y)

            self.update()
Exemplo n.º 10
0
 def _refresh_scene(self):
     self._scene.clear()
     self.spriteList.clear()
     for k in self._sprites.keys():
         sprite = self._sprites[k]
         self.spriteList.addItem(k)
         if not sprite["is_text"]:
             if sprite["render"]["enable"]:
                 sprite_path = os.path.join(self._currentProject, sprite["path"])
                 sprite_obj = json.loads(open(sprite_path).read())
                 image_path = os.path.join(os.path.split(sprite_path)[0], sprite_obj["image"]["path"])
                 pixmap = QPixmap(image_path)
                 slice_col = sprite_obj["image"]["col"]
                 slice_row = sprite_obj["image"]["row"]
                 slice_width = pixmap.width() // slice_col
                 slice_height = pixmap.height() // slice_row
                 slice_index = sprite["render"]["default_frame"]
                 pixmap = pixmap.copy(
                     QRect(
                         (slice_index % slice_col) * slice_width,
                         (slice_index // slice_col) * slice_height,
                         slice_width, slice_height))
                 pixmap = pixmap.scaledToWidth(int(pixmap.width() * sprite["render"]["render_scale"]))
                 pixmap = QPixmap.fromImage(pixmap.toImage().mirrored(sprite["render"]["flipX"], False))
                 pixmap_item = self._scene.addPixmap(pixmap)
                 pixmap_item.setPos(sprite["transform"]["position"]["x"], -sprite["transform"]["position"]["y"])
                 pixmap_item.moveBy(pixmap.width() // -2, pixmap.height() // -2)
                 pixmap_item.moveBy(self.sceneView.width() // 2, self.sceneView.height() // 2)
                 pixmap_item.setZValue(sprite["render"]["layer"])
             if sprite["collision"]["enable"]:
                 pen = QPen(Qt.green, 1, Qt.SolidLine)
                 c_width = sprite["collision"]["x_size"]
                 c_height = sprite["collision"]["y_size"]
                 collision_item = self._scene.addRect(QRectF(
                     sprite["transform"]["position"]["x"] - c_width // 2,
                     -sprite["transform"]["position"]["y"] - c_height // 2,
                     c_width,
                     c_height
                 ), pen)
                 collision_item.moveBy(self.sceneView.width() // 2, self.sceneView.height() // 2)
                 collision_item.setZValue(sprite["render"]["layer"])
         else:
             if sprite["render"]["enable"]:
                 text_item = self._scene.addText(
                     sprite["content"] if len(sprite["content"]) > 0 else k, QFont("Arial", 20))
                 text_item.setScale(sprite["render"]["render_scale"])
                 text_item.setPos(sprite["transform"]["position"]["x"], -sprite["transform"]["position"]["y"])
                 text_item.moveBy(self.sceneView.width() // 2, self.sceneView.height() // 2)
                 text_item.setZValue(sprite["render"]["layer"])
                 text_item.setDefaultTextColor(Qt.red)
     pen = QPen(Qt.darkGray, 1, Qt.DotLine)
     self._scene.addLine(
         QLineF(
             0, self.sceneView.height() / 2,
             self.sceneView.width(), self.sceneView.height() / 2), pen).setZValue(9999)
     self._scene.addLine(
         QLineF(
             self.sceneView.width() / 2, 0,
             self.sceneView.width() / 2, self.sceneView.height()), pen).setZValue(9999)
Exemplo n.º 11
0
class ThumbLabel(QLabel):
    def __init__(
            self, widget, canvas, appwindow,
            CameraPos):  #related to the cavans for recovering the Thumblabel
        if widget != None:
            super().__init__(
                widget)  #previous implmentation for adding in centralwidget
        else:
            super().__init__()  #derictly with QLabel for QlistView
        self.Canvas = canvas
        self.background_color = QColor(Qt.white)
        self.bigpixmap = QPixmap(256, 256)
        self.bigpixmap.fill(self.background_color)  #default white
        self.CameraPos = CameraPos
        self.AppWindow = appwindow
        self.grid = None  # try later
        self.reset()

    def update_grid(self, newgrid):
        self.grid = newgrid

    def reset(self):
        # Create the pixmap for display.
        self.setScaledContents(True)
        self.setPixmap(QPixmap(36, 36))
        self.setMinimumSize(1, 1)
        self.setMaximumSize(36, 36)  #currently
        # Clear the canvas.
        self.pixmap().fill(self.background_color)

    def setbigmap(self, pixmap):
        self.bigpixmap = pixmap.copy()  #copy to avoid memory problem

    def mouseDoubleClickEvent(self, event):
        pixmap = self.bigpixmap.copy()  #recover thumbnail to canvas
        self.Canvas.setPixmap(pixmap)
        self.update_grid(self.AppWindow.getgrid())
        #print(self.CameraPos)
        #global globalGrid

        if self.grid is not None:
            rd.update_image(self.CameraPos, self.grid, "opened")
        else:
            print("Grid is None")

        if self.AppWindow is not None:
            self.AppWindow.Update_image()
        else:
            print("AppWindow is None")

    def setCanvas(self, canvas):
        self.Canvas = canvas

    def setCameraPos(self, camerapos):
        self.Camerapos = camerapos

    def setPaintWindow(self, window):
        self.AppWindow = window
Exemplo n.º 12
0
 def loadFile(self, fileName):
     newImage = QPixmap(fileName)
     if newImage.isNull():
         newImage = QPixmap("thumbnails/black480x360.jpg")
     cropRect = QRect(0, 45, 480, 270)
     croppedImage = newImage.copy(cropRect)
     self.thumbnail.setPixmap(
         croppedImage.scaledToWidth(self.thumbnail.width(),
                                    Qt.SmoothTransformation))
 def cropToReference(to_be_cropped_pixmap: QtGui.QPixmap,
                     reference_pixmap: QtGui.QPixmap) -> QtGui.QPixmap:
     #help by goetz from https://forum.qt.io/topic/13421/how-to-rotate-a-content-of-qpixmap-without-changing-size/3
     reference_width = reference_pixmap.width()
     reference_height = reference_pixmap.height()
     xoffset = (to_be_cropped_pixmap.width() - reference_width) / 2
     yoffset = (to_be_cropped_pixmap.height() - reference_height) / 2
     return to_be_cropped_pixmap.copy(xoffset, yoffset, reference_width,
                                      reference_height)
Exemplo n.º 14
0
    def initUI(self):
        self.pixmap = QPixmap('start.png')
        self.label_img = QLabel()
        self.label_img.setObjectName("image")
        self.pixmapOriginal = QPixmap.copy(self.pixmap)

        self.drawing = False
        self.lastPoint = QPoint()
        hbox = QHBoxLayout(self.label_img)
        self.setLayout(hbox)
Exemplo n.º 15
0
 def initialize_sprites(self):
     data, script = self.data, self.script_module
     sprites = {}
     for k in data["sprites"].keys():
         sprite = data["sprites"][k]
         if sprite["script"]["class_name"] != "":
             sprite_instance = Misc.get_sprite(
                 script, sprite["script"]["class_name"])
         else:
             sprite_instance = Sprite()
         sprite_instance.class_name = sprite["script"]["class_name"]
         sprite_instance.input = self.input
         sprite_instance.sound = self.sound
         sprite_instance.game_application = self
         sprite_position = sprite["transform"]["position"]
         sprite_instance.transform.position = Vector2(
             sprite_position["x"], sprite_position["y"])
         sprite_instance.render.enable = sprite["render"]["enable"]
         sprite_instance.render.layer = sprite["render"]["layer"]
         sprite_instance.render.scale = sprite["render"]["render_scale"]
         sprite_instance.is_text = sprite["is_text"]
         if not sprite["is_text"]:
             sprite_instance.render.flipX = sprite["render"]["flipX"]
             sprite_instance.render.default_frame = sprite["render"][
                 "default_frame"]
             sprite_instance.collision.enable = sprite["collision"][
                 "enable"]
             sprite_instance.collision.size.x = sprite["collision"][
                 "x_size"]
             sprite_instance.collision.size.y = sprite["collision"][
                 "y_size"]
             sprite_instance.animator.triggers = sprite["sprite"][
                 "triggers"]
             sprite_instance.animator.animations = sprite["sprite"][
                 "animations"]
             sprite_instance.animator.transitions = sprite["sprite"][
                 "transitions"]
             pixmap = QPixmap()
             pixmap.loadFromData(
                 base64.b64decode(sprite["sprite"]["image"]["data"]))
             slice_width = pixmap.width(
             ) // sprite["sprite"]["image"]["col"]
             slice_height = pixmap.height(
             ) // sprite["sprite"]["image"]["row"]
             for y in range(sprite["sprite"]["image"]["row"]):
                 for x in range(sprite["sprite"]["image"]["col"]):
                     frame = pixmap.copy(
                         QRect(x * slice_width, y * slice_height,
                               slice_width, slice_height))
                     sprite_instance.animator.frames.append(frame)
         else:
             sprite_instance.context = sprite["content"]
         sprite_instance.script_instance = sprite_instance
         sprites[k] = sprite_instance
     return sprites
Exemplo n.º 16
0
    def unpack_sprites(self, filename):
        input_pixmap = QPixmap(filename)
        frame_count = input_pixmap.width() // self.frame_size.width()
        width = self.frame_size.width()
        sprites = []

        for current_frame in range(1, frame_count+1):
            sprites.append(input_pixmap.copy(current_frame * width, 0,
                                             width, self.frame_size.height()))

        return sprites
Exemplo n.º 17
0
 def push(self, pixmap: QPixmap):
     # 在中間插入
     if self.index < (len(self.data) - 1):
         del self.data[self.index + 1:]
     new_index = min(self.index + 1, MAX_BUFFER_SIZE)
     # 超過上限,從 buffer 移除最舊的一筆
     if new_index == self.index:
         self.data.pop(0)
     self.index = new_index
     pm = pixmap.copy()
     self.data.append(pm)
Exemplo n.º 18
0
	def updateAppQRCode(self, target, qrCodePng):
		qrCodePixmap = QPixmap()
		qrCodePixmap.loadFromData(
			qrCodePng, 'png', QtCore.Qt.MonoOnly )
		border = 10 #px
		qrCodePixmap = qrCodePixmap.copy(QtCore.QRect(
			border, border,
			qrCodePixmap.width() - border*2, qrCodePixmap.height() - border*2
		))
		target.setPixmap(qrCodePixmap)
		target.show()
Exemplo n.º 19
0
 def mouseMoveEvent(self, event):
     self.parent.cursorPos.setText('({}, {})'
                                 .format(event.pos().x(), event.pos().y()))
     if event.buttons() and Qt.LeftButton and self.drawing:
         self.pixmap = QPixmap.copy(self.prev_pixmap)
         painter = QPainter(self.pixmap)
         painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
         p1_x, p1_y = self.lastPoint.x(), self.lastPoint.y()
         p2_x, p2_y = event.pos().x(), event.pos().y()
         painter.drawRect(min(p1_x, p2_x), min(p1_y, p2_y), 
                           abs(p1_x-p2_x), abs(p1_y-p2_y))
         self.update()
Exemplo n.º 20
0
    def setPixmap(self, pixmap: QPixmap):
        # self.imgPixmap = pixmap  # 载入图片
        # self.scaledImg = self.imgPixmap.copy()  # 初始化缩放图
        # # self.scaledImg = self.imgPixmap.scaled(self.size())  # 初始化缩放图
        # # self.singleOffset = QPoint(0, 0)
        # self.repaint()

        # self.resize(500, 500)  # 设定窗口大小(根据自己显示图片的大小,可更改)
        # self.setWindowTitle("图片操作")  # 设定窗口名称

        self.imgPixmap = pixmap.copy()  # 载入图片
        # self.scaledImg = self.imgPixmap.scaled(self.size())  # 初始化缩放图
        self.scaledImg = pixmap.copy()  # 初始化缩放图
        self.imageorsize = [(self.width() - pixmap.width()) / 2,
                            (self.height() - pixmap.height()) / 2]
        # print(self.imageorsize)
        self.singleOffset = QPoint(self.imageorsize[0],
                                   self.imageorsize[1])  # 初始化偏移值
        self.isLeftPressed = bool(False)  # 图片被点住(鼠标左键)标志位
        self.isImgLabelArea = bool(True)  # 鼠标进入label图片显示区域
        self.repaint()
Exemplo n.º 21
0
class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.origin_pixmap = QPixmap("apple.jpg")
        self.init_ui()

    def init_ui(self):
        self.setMinimumWidth(320)
        self.setMinimumHeight(240)
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        self.setLayout(layout)

        lb_1 = QLabel()
        self.origin_pixmap = self.origin_pixmap.scaledToHeight(240)  # 사이즈가 조정
        lb_1.setPixmap(self.origin_pixmap)
        layout.addWidget(lb_1)

        # 자를 영역 선택, 복사
        rect = QRect(50, 50, 50, 50)
        cropped = self.origin_pixmap.copy(rect)

        self.lb_2 = QLabel()
        self.lb_2.setPixmap(cropped)
        self.lb_2.setFixedSize(100, 100)
        layout.addWidget(self.lb_2)

        w = Rectangle(parent=lb_1)
        w.setGeometry(0, 0, 100, 100)
        w.setStyleSheet("background-color: red")
        opacity_effect = QGraphicsOpacityEffect(self)
        opacity_effect.setOpacity(0.3)
        w.setGraphicsEffect(opacity_effect)

        w.change_position.connect(self.crop_image)

    @pyqtSlot(QRect, name="cropImage")
    def crop_image(self, crop_rect):
        # 자를 영역 선택, 복사
        cropped = self.origin_pixmap.copy(crop_rect)
        self.lb_2.setPixmap(cropped)
Exemplo n.º 22
0
 def __init__(self, path, image_width, image_height, image_total, line_count=10):
     super().__init__()
     image = QPixmap(path)
     self.path = path
     self.line_count = line_count
     self.image_width = image_width
     self.image_height = image_height
     self._images = []
     for i in range(image_total):
         x = i % self.line_count
         y = i // self.line_count
         self._images.append(image.copy(x * self.image_width, y * self.image_height,
                                        self.image_width, self.image_height))
Exemplo n.º 23
0
 def paintEvent(self, event):
     super().paintEvent(event)
     if self.switch:
         rect =QRect(self.x0, self.y0, abs(self.x1-self.x0), abs(self.y1-self.y0))
         painter = QPainter(self)
         painter.setPen(QPen(Qt.gray, 1, Qt.SolidLine))
         painter.drawRect(rect)
         #pqscreen  = QGuiApplication.primaryScreen()
         #pixmap2 = pqscreen.grabWindow(1, self.x0, self.y0, abs(self.x1-self.x0), abs(self.y1-self.y0))
         #pixmap2.save('0000.png')
         pixmap = QPixmap.copy(self.pixmap, rect)
         pixmap.save('temp/cut.jpg')
         self.ok = True
Exemplo n.º 24
0
 def drawCloudImage(self, painter):
     if self.fir.raw():
         pixmap = QPixmap()
         pixmap.loadFromData(self.fir.raw())
         self.imageSize = pixmap.size()
         rect = QRect(*self.fir.rect())
         image = pixmap.copy(rect)
         painter.drawPixmap(0, 0, image)
     else:
         rect = QRect(0, 0, 260, 260)
         painter.setPen(Qt.DashLine)
         painter.drawRect(rect)
         painter.drawText(rect, Qt.AlignCenter, QCoreApplication.translate('Editor', 'No Satellite Image'))
Exemplo n.º 25
0
    def selectionDone(self):
        """
        This function stop the selection when it's done.
        """
        self.qcheckbox_show_filter.setDisabled(False)

        image = self.imageArray[self.image_index]

        image = QImage(image, image.shape[1], image.shape[0],
                       QImage.Format_Indexed8)
        pix = QPixmap(image)

        self.selectedPixmap = pix.copy(self.label_image.rubberBand.geometry())
Exemplo n.º 26
0
class Animation(QThread):
    trigger = pyqtSignal(QPixmap)
    def __init__(self, parent):
        super().__init__()
        self.contador = 0
        self.link = MovilLabel(parent)
        self.pixmap = QPixmap("./IMGS/link.png")
        # print(self.pixmap.width(), self.pixmap.height())
        pixmap = self.pixmap.copy(QRect(0, 910, 120, 1040))
        self.link.setPixmap(pixmap)
        self.link.setGeometry(0, 500, 120, 130)
        self.trigger.connect(parent.animar)

    def run(self):
        while True:
            sleep(0.01)
            pixmap = self.pixmap.copy(
                QRect(120 * self.contador, 910, 120 * (self.contador + 1),
                      1040))
            self.contador += 1
            if self.contador >= 10:
                self.contador = 0
            self.link.setPixmap(pixmap)
Exemplo n.º 27
0
class ChartPatternModel(abstract.AbstractListModel):
    def __init__(self, parent=None):
        super(ChartPatternModel, self).__init__(parent)
        self.patternImage = QPixmap(":/img/patterns.png")
        self._foreColor = QColor(Qt.black)
        self._backColor = QColor(Qt.white)

        self.beginResetModel()
        self.setRowSize(48 + 1)  # patterns + one solid
        self.endResetModel()

    def setForeColor(self, color):
        self._foreColor = color

    def setBackColor(self, color):
        self._backColor = color

    def foreColor(self):
        return self._foreColor

    def backColor(self):
        return self._backColor

    def data(self, index=QModelIndex(), role=Qt.DisplayRole):
        if role not in [Qt.DecorationRole, Qt.EditRole]:
            return QVariant()
        if role == Qt.DecorationRole:
            img = None
            # solid special case
            if index.row() == 0:
                img = QPixmap(48, 48)
                img.fill(Qt.black)
            # pattern case
            else:
                img = self.patternImage.copy(48 * (index.row() - 1), 0, 48, 48)
            foreMask = img.createMaskFromColor(QColor(Qt.white))
            backMask = img.createMaskFromColor(QColor(Qt.black))
            p = QPainter(img)
            p.setPen(self.foreColor())
            p.drawPixmap(img.rect(), foreMask, foreMask.rect())
            p.setPen(self.backColor())
            p.drawPixmap(img.rect(), backMask, backMask.rect())
            p.end()
            return img
        elif role == Qt.EditRole:
            if index.row() == 0:
                return -2  # solid special case
            else:
                return index.row()
        return QVariant()
Exemplo n.º 28
0
    def setPixmap(self, image_fn):
        self.pixmap = QPixmap(image_fn)
        self.W, self.H = self.pixmap.width(), self.pixmap.height()

        if self.H > self.screen_height * 0.8:
            resize_ratio = (self.screen_height * 0.8) / self.H
            self.W = round(self.W * resize_ratio)
            self.H = round(self.H * resize_ratio)
            self.pixmap = QPixmap.scaled(self.pixmap, self.W, self.H,
                                transformMode=Qt.SmoothTransformation)
        
        self.parent.imageSize.setText('{}x{}'.format(self.W, self.H))
        self.setFixedSize(self.W, self.H)
        self.pixmapOriginal = QPixmap.copy(self.pixmap)
Exemplo n.º 29
0
 def drawResultBox(self):
     res = QPixmap.copy(self.pixmapOriginal)
     painter = QPainter(res)
     font = QFont('mono', 15, 1)
     painter.setFont(font)
     painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
     for box in self.results:
         lx, ly, rx, ry = box[:4]
         painter.drawRect(lx, ly, rx-lx, ry-ly)
         if len(box) == 5:
             painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
             painter.drawText(lx, ly+15, self.key_config[box[-1]])
             painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
     return res
Exemplo n.º 30
0
class Field:
    """Defines the field of battleships


    Have list shot where coordinates are marked as shot
    Have list ships where all Ship objects are stored
    fieldUI uses field.png pixmap"""
    def __init__(self):
        """shot value list:
         True - hit
         False - miss
         number diffrent to -1 - there is a ship in this position"""
        self.shot = []

        emptyList = []  # Temporary variable for fulfilling the shot list

        # Fulfilling shot list as empty
        for i in range(0, 10):
            emptyList = []
            for j in range(0, 10):
                emptyList.append(-1)
            self.shot.append(emptyList)

        del emptyList  # We won't need this list anymore

        self.ships = []
        self.fieldUI = QPixmap("res/pictures/field.png")

    def change_field(self, filename, x, y):
        """Method changes graphic on field - adds new image

        x, y - coordinates where new graphic should be
        filename - path to image"""

        new_image = QPixmap(filename)
        merge = self.fieldUI.copy()
        painter = QPainter(merge)

        painter.drawPixmap(x, y, new_image)
        painter.end()
        self.fieldUI = QPixmap(merge)

    def __str__(self):
        for i in range(0, 10):
            for j in range(0, 10):
                print("%5d (%d %d)" % (self.shot[j][i], j, i), " ", end="")
            print()
        return ""
Exemplo n.º 31
0
def get_spell_icon(icon_index):
    # Spell Icons are 40x40 pixels
    file_number = math.ceil(icon_index / 36)
    file_name = "data/spells/spells0" + str(file_number) + ".png"
    spell_number = icon_index % 36
    file_row = math.floor((spell_number + 6) / 6)
    file_col = spell_number % 6 + 1
    x = (file_col - 1) * 40
    y = (file_row - 1) * 40
    icon_image = QPixmap(file_name)
    scaled_icon_image = icon_image.copy(QRect(x, y, 40, 40)).scaled(
        18, 18, transformMode=Qt.SmoothTransformation)
    label = QLabel()
    label.setPixmap(scaled_icon_image)
    label.setFixedSize(18, 18)
    return label
Exemplo n.º 32
0
def getPreview(save):
    save = BlackAndWhite2SaveGame(save)
    lines = [
        [
            (u"Name : " + save.getName(), Qt.AlignLeft),
            (u"| Profile : " + save.getSaveGroupIdentifier()[1:], Qt.AlignLeft),
        ],
        [(u"Land number : " + save.getLand(), Qt.AlignLeft)],
        [(u"Saved at : " + save.getCreationTime().toString(), Qt.AlignLeft)],
        [(u"Elapsed time : " + save.getElapsed(), Qt.AlignLeft)],
    ]

    pixmap = QPixmap(320, 320)
    pixmap.fill()
    # rightBuffer = []

    painter = QPainter()
    painter.begin(pixmap)
    fm = painter.fontMetrics()
    margin = 5
    height = 0
    width = 0
    ln = 0
    for line in lines:

        cHeight = 0
        cWidth = 0

        for (toPrint, align) in line:
            bRect = fm.boundingRect(toPrint)
            cHeight = bRect.height() * (ln + 1)
            bRect.moveTop(cHeight - bRect.height())
            if align != Qt.AlignLeft:
                continue
            else:
                bRect.moveLeft(cWidth + margin)
            cWidth = cWidth + bRect.width()
            painter.drawText(bRect, align, toPrint)

        height = max(height, cHeight)
        width = max(width, cWidth + (2 * margin))
        ln = ln + 1
    # height = height + lh

    painter.end()

    return pixmap.copy(0, 0, width, height)
Exemplo n.º 33
0
    def setupGame(self, pic):
        # reset time and restart timer
        self.stop = False
        self.time = 0
        self.timer = updateTimeThread(self)
        self.timer.daemon = True
        self.timer.start()

        # reset moves and label of moves
        self.moves = 0
        self.labelMoves.setText(str(self.moves))

        # transform the user's picture to a pixmap
        pixmap = QPixmap(pic)
        # scale the pixmap to fit the 160x160 game widget
        pixmap = pixmap.scaled(160, 160,
                               Qt.KeepAspectRatioByExpanding,
                               Qt.SmoothTransformation)

        # split pixmap and assign splitted pixmaps to tiles
        for label in self.labels:
            label.setPixmap(pixmap.copy(label.pos().x(),
                                        label.pos().y(),
                                        40,
                                        40))

        # top-left tile is empty.
        self.labels[0].isEmpty = True
        self.labels[0].setPixmap(QPixmap())

        # allow moving of tiles
        self.setMoveEnabled(True)

        # randomize position of tiles by switching them (animations turned off)
        for i in range(200):
            index = random.choice(range(16))
            self.labels[index].switch(False)
Exemplo n.º 34
0
class SnapshotRegionGrabber(QWidget):
    """
    Class implementing a grabber widget for a rectangular snapshot region.
    
    @signal grabbed(QPixmap) emitted after the region was grabbed
    """
    grabbed = pyqtSignal(QPixmap)
    
    StrokeMask = 0
    FillMask = 1
    
    Rectangle = 0
    Ellipse = 1
    
    def __init__(self, mode=Rectangle):
        """
        Constructor
        
        @param mode region grabber mode (SnapshotRegionGrabber.Rectangle or
            SnapshotRegionGrabber.Ellipse)
        """
        super(SnapshotRegionGrabber, self).__init__(
            None,
            Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint |
            Qt.FramelessWindowHint | Qt.Tool)
        
        assert mode in [SnapshotRegionGrabber.Rectangle,
                        SnapshotRegionGrabber.Ellipse]
        self.__mode = mode
        
        self.__selection = QRect()
        self.__mouseDown = False
        self.__newSelection = False
        self.__handleSize = 10
        self.__mouseOverHandle = None
        self.__showHelp = True
        self.__grabbing = False
        self.__dragStartPoint = QPoint()
        self.__selectionBeforeDrag = QRect()
        
        # naming conventions for handles
        # T top, B bottom, R Right, L left
        # 2 letters: a corner
        # 1 letter: the handle on the middle of the corresponding side
        self.__TLHandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__TRHandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__BLHandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__BRHandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__LHandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__THandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__RHandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__BHandle = QRect(0, 0, self.__handleSize, self.__handleSize)
        self.__handles = [self.__TLHandle, self.__TRHandle, self.__BLHandle,
                          self.__BRHandle, self.__LHandle, self.__THandle,
                          self.__RHandle, self.__BHandle]
        self.__helpTextRect = QRect()
        self.__helpText = self.tr(
            "Select a region using the mouse. To take the snapshot, press"
            " the Enter key or double click. Press Esc to quit.")
        
        self.__pixmap = QPixmap()
        
        self.setMouseTracking(True)
        
        QTimer.singleShot(200, self.__initialize)
    
    def __initialize(self):
        """
        Private slot to initialize the rest of the widget.
        """
        self.__desktop = QApplication.desktop()
        x = self.__desktop.x()
        y = self.__desktop.y()
        if qVersion() >= "5.0.0":
            self.__pixmap = QApplication.screens()[0].grabWindow(
                self.__desktop.winId(), x, y,
                self.__desktop.width(), self.__desktop.height())
        else:
            self.__pixmap = QPixmap.grabWindow(
                self.__desktop.winId(), x, y,
                self.__desktop.width(), self.__desktop.height())
        self.resize(self.__pixmap.size())
        self.move(x, y)
        self.setCursor(Qt.CrossCursor)
        self.show()

        self.grabMouse()
        self.grabKeyboard()
    
    def paintEvent(self, evt):
        """
        Protected method handling paint events.
        
        @param evt paint event (QPaintEvent)
        """
        if self.__grabbing:     # grabWindow() should just get the background
            return
        
        painter = QPainter(self)
        pal = QPalette(QToolTip.palette())
        font = QToolTip.font()
        
        handleColor = pal.color(QPalette.Active, QPalette.Highlight)
        handleColor.setAlpha(160)
        overlayColor = QColor(0, 0, 0, 160)
        textColor = pal.color(QPalette.Active, QPalette.Text)
        textBackgroundColor = pal.color(QPalette.Active, QPalette.Base)
        painter.drawPixmap(0, 0, self.__pixmap)
        painter.setFont(font)
        
        r = QRect(self.__selection)
        if not self.__selection.isNull():
            grey = QRegion(self.rect())
            if self.__mode == SnapshotRegionGrabber.Ellipse:
                reg = QRegion(r, QRegion.Ellipse)
            else:
                reg = QRegion(r)
            grey = grey.subtracted(reg)
            painter.setClipRegion(grey)
            painter.setPen(Qt.NoPen)
            painter.setBrush(overlayColor)
            painter.drawRect(self.rect())
            painter.setClipRect(self.rect())
            drawRect(painter, r, handleColor)
        
        if self.__showHelp:
            painter.setPen(textColor)
            painter.setBrush(textBackgroundColor)
            self.__helpTextRect = painter.boundingRect(
                self.rect().adjusted(2, 2, -2, -2),
                Qt.TextWordWrap, self.__helpText).translated(
                -self.__desktop.x(), -self.__desktop.y())
            self.__helpTextRect.adjust(-2, -2, 4, 2)
            drawRect(painter, self.__helpTextRect, textColor,
                     textBackgroundColor)
            painter.drawText(
                self.__helpTextRect.adjusted(3, 3, -3, -3),
                Qt.TextWordWrap, self.__helpText)
        
        if self.__selection.isNull():
            return
        
        # The grabbed region is everything which is covered by the drawn
        # rectangles (border included). This means that there is no 0px
        # selection, since a 0px wide rectangle will always be drawn as a line.
        txt = "{0:n}, {1:n} ({2:n} x {3:n})".format(
            self.__selection.x(), self.__selection.y(),
            self.__selection.width(), self.__selection.height())
        textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt)
        boundingRect = textRect.adjusted(-4, 0, 0, 0)
        
        if textRect.width() < r.width() - 2 * self.__handleSize and \
           textRect.height() < r.height() - 2 * self.__handleSize and \
           r.width() > 100 and \
           r.height() > 100:
            # center, unsuitable for small selections
            boundingRect.moveCenter(r.center())
            textRect.moveCenter(r.center())
        elif r.y() - 3 > textRect.height() and \
                r.x() + textRect.width() < self.rect().width():
            # on top, left aligned
            boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3))
            textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3))
        elif r.x() - 3 > textRect.width():
            # left, top aligned
            boundingRect.moveTopRight(QPoint(r.x() - 3, r.y()))
            textRect.moveTopRight(QPoint(r.x() - 5, r.y()))
        elif r.bottom() + 3 + textRect.height() < self.rect().bottom() and \
                r.right() > textRect.width():
            # at bottom, right aligned
            boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3))
            textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3))
        elif r.right() + textRect.width() + 3 < self.rect().width():
            # right, bottom aligned
            boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom()))
            textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom()))
        
        # If the above didn't catch it, you are running on a very
        # tiny screen...
        drawRect(painter, boundingRect, textColor, textBackgroundColor)
        painter.drawText(textRect, Qt.AlignHCenter, txt)
        
        if (r.height() > self.__handleSize * 2 and
            r.width() > self.__handleSize * 2) or \
           not self.__mouseDown:
            self.__updateHandles()
            painter.setPen(Qt.NoPen)
            painter.setBrush(handleColor)
            painter.setClipRegion(
                self.__handleMask(SnapshotRegionGrabber.StrokeMask))
            painter.drawRect(self.rect())
            handleColor.setAlpha(60)
            painter.setBrush(handleColor)
            painter.setClipRegion(
                self.__handleMask(SnapshotRegionGrabber.FillMask))
            painter.drawRect(self.rect())
    
    def resizeEvent(self, evt):
        """
        Protected method to handle resize events.
        
        @param evt resize event (QResizeEvent)
        """
        if self.__selection.isNull():
            return
        
        r = QRect(self.__selection)
        r.setTopLeft(self.__limitPointToRect(r.topLeft(), self.rect()))
        r.setBottomRight(self.__limitPointToRect(r.bottomRight(), self.rect()))
        if r.width() <= 1 or r.height() <= 1:
            # This just results in ugly drawing...
            self.__selection = QRect()
        else:
            self.__selection = self.__normalizeSelection(r)
    
    def mousePressEvent(self, evt):
        """
        Protected method to handle mouse button presses.
        
        @param evt mouse press event (QMouseEvent)
        """
        self.__showHelp = not self.__helpTextRect.contains(evt.pos())
        if evt.button() == Qt.LeftButton:
            self.__mouseDown = True
            self.__dragStartPoint = evt.pos()
            self.__selectionBeforeDrag = QRect(self.__selection)
            if not self.__selection.contains(evt.pos()):
                self.__newSelection = True
                self.__selection = QRect()
            else:
                self.setCursor(Qt.ClosedHandCursor)
        elif evt.button() == Qt.RightButton:
            self.__newSelection = False
            self.__selection = QRect()
            self.setCursor(Qt.CrossCursor)
        self.update()
    
    def mouseMoveEvent(self, evt):
        """
        Protected method to handle mouse movements.
        
        @param evt mouse move event (QMouseEvent)
        """
        shouldShowHelp = not self.__helpTextRect.contains(evt.pos())
        if shouldShowHelp != self.__showHelp:
            self.__showHelp = shouldShowHelp
            self.update()
        
        if self.__mouseDown:
            if self.__newSelection:
                p = evt.pos()
                r = self.rect()
                self.__selection = self.__normalizeSelection(
                    QRect(self.__dragStartPoint,
                          self.__limitPointToRect(p, r)))
            elif self.__mouseOverHandle is None:
                # moving the whole selection
                r = self.rect().normalized()
                s = self.__selectionBeforeDrag.normalized()
                p = s.topLeft() + evt.pos() - self.__dragStartPoint
                r.setBottomRight(
                    r.bottomRight() - QPoint(s.width(), s.height()) +
                    QPoint(1, 1))
                if not r.isNull() and r.isValid():
                    self.__selection.moveTo(self.__limitPointToRect(p, r))
            else:
                # dragging a handle
                r = QRect(self.__selectionBeforeDrag)
                offset = evt.pos() - self.__dragStartPoint
                
                if self.__mouseOverHandle in \
                   [self.__TLHandle, self.__THandle, self.__TRHandle]:
                    r.setTop(r.top() + offset.y())
                
                if self.__mouseOverHandle in \
                   [self.__TLHandle, self.__LHandle, self.__BLHandle]:
                    r.setLeft(r.left() + offset.x())
                
                if self.__mouseOverHandle in \
                   [self.__BLHandle, self.__BHandle, self.__BRHandle]:
                    r.setBottom(r.bottom() + offset.y())
                
                if self.__mouseOverHandle in \
                   [self.__TRHandle, self.__RHandle, self.__BRHandle]:
                    r.setRight(r.right() + offset.x())
                
                r.setTopLeft(self.__limitPointToRect(r.topLeft(), self.rect()))
                r.setBottomRight(
                    self.__limitPointToRect(r.bottomRight(), self.rect()))
                self.__selection = self.__normalizeSelection(r)
            
            self.update()
        else:
            if self.__selection.isNull():
                return
            
            found = False
            for r in self.__handles:
                if r.contains(evt.pos()):
                    self.__mouseOverHandle = r
                    found = True
                    break
            
            if not found:
                self.__mouseOverHandle = None
                if self.__selection.contains(evt.pos()):
                    self.setCursor(Qt.OpenHandCursor)
                else:
                    self.setCursor(Qt.CrossCursor)
            else:
                if self.__mouseOverHandle in [self.__TLHandle,
                                              self.__BRHandle]:
                    self.setCursor(Qt.SizeFDiagCursor)
                elif self.__mouseOverHandle in [self.__TRHandle,
                                                self.__BLHandle]:
                    self.setCursor(Qt.SizeBDiagCursor)
                elif self.__mouseOverHandle in [self.__LHandle,
                                                self.__RHandle]:
                    self.setCursor(Qt.SizeHorCursor)
                elif self.__mouseOverHandle in [self.__THandle,
                                                self.__BHandle]:
                    self.setCursor(Qt.SizeVerCursor)
    
    def mouseReleaseEvent(self, evt):
        """
        Protected method to handle mouse button releases.
        
        @param evt mouse release event (QMouseEvent)
        """
        self.__mouseDown = False
        self.__newSelection = False
        if self.__mouseOverHandle is None and \
           self.__selection.contains(evt.pos()):
            self.setCursor(Qt.OpenHandCursor)
        self.update()
    
    def mouseDoubleClickEvent(self, evt):
        """
        Protected method to handle mouse double clicks.
        
        @param evt mouse double click event (QMouseEvent)
        """
        self.__grabRect()
    
    def keyPressEvent(self, evt):
        """
        Protected method to handle key presses.
        
        @param evt key press event (QKeyEvent)
        """
        if evt.key() == Qt.Key_Escape:
            self.grabbed.emit(QPixmap())
        elif evt.key() in [Qt.Key_Enter, Qt.Key_Return]:
            self.__grabRect()
        else:
            evt.ignore()
    
    def __updateHandles(self):
        """
        Private method to update the handles.
        """
        r = QRect(self.__selection)
        s2 = self.__handleSize // 2
        
        self.__TLHandle.moveTopLeft(r.topLeft())
        self.__TRHandle.moveTopRight(r.topRight())
        self.__BLHandle.moveBottomLeft(r.bottomLeft())
        self.__BRHandle.moveBottomRight(r.bottomRight())
        
        self.__LHandle.moveTopLeft(QPoint(r.x(), r.y() + r.height() // 2 - s2))
        self.__THandle.moveTopLeft(QPoint(r.x() + r.width() // 2 - s2, r.y()))
        self.__RHandle.moveTopRight(
            QPoint(r.right(), r.y() + r.height() // 2 - s2))
        self.__BHandle.moveBottomLeft(
            QPoint(r.x() + r.width() // 2 - s2, r.bottom()))
    
    def __handleMask(self, maskType):
        """
        Private method to calculate the handle mask.
        
        @param maskType type of the mask to be used
            (SnapshotRegionGrabber.FillMask or
            SnapshotRegionGrabber.StrokeMask)
        @return calculated mask (QRegion)
        """
        mask = QRegion()
        for rect in self.__handles:
            if maskType == SnapshotRegionGrabber.StrokeMask:
                r = QRegion(rect)
                mask += r.subtracted(QRegion(rect.adjusted(1, 1, -1, -1)))
            else:
                mask += QRegion(rect.adjusted(1, 1, -1, -1))
        return mask
    
    def __limitPointToRect(self, point, rect):
        """
        Private method to limit the given point to the given rectangle.
        
        @param point point to be limited (QPoint)
        @param rect rectangle the point shall be limited to (QRect)
        @return limited point (QPoint)
        """
        q = QPoint()
        if point.x() < rect.x():
            q.setX(rect.x())
        elif point.x() < rect.right():
            q.setX(point.x())
        else:
            q.setX(rect.right())
        if point.y() < rect.y():
            q.setY(rect.y())
        elif point.y() < rect.bottom():
            q.setY(point.y())
        else:
            q.setY(rect.bottom())
        return q
    
    def __normalizeSelection(self, sel):
        """
        Private method to normalize the given selection.
        
        @param sel selection to be normalized (QRect)
        @return normalized selection (QRect)
        """
        rect = QRect(sel)
        if rect.width() <= 0:
            left = rect.left()
            width = rect.width()
            rect.setLeft(left + width - 1)
            rect.setRight(left)
        if rect.height() <= 0:
            top = rect.top()
            height = rect.height()
            rect.setTop(top + height - 1)
            rect.setBottom(top)
        return rect
    
    def __grabRect(self):
        """
        Private method to grab the selected rectangle (i.e. do the snapshot).
        """
        if self.__mode == SnapshotRegionGrabber.Ellipse:
            ell = QRegion(self.__selection, QRegion.Ellipse)
            if not ell.isEmpty():
                self.__grabbing = True
                
                xOffset = self.__pixmap.rect().x() - ell.boundingRect().x()
                yOffset = self.__pixmap.rect().y() - ell.boundingRect().y()
                translatedEll = ell.translated(xOffset, yOffset)
                
                pixmap2 = QPixmap(ell.boundingRect().size())
                pixmap2.fill(Qt.transparent)
                
                pt = QPainter()
                pt.begin(pixmap2)
                if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff):
                    pt.setRenderHints(
                        QPainter.Antialiasing |
                        QPainter.HighQualityAntialiasing |
                        QPainter.SmoothPixmapTransform,
                        True)
                    pt.setBrush(Qt.black)
                    pt.setPen(QPen(QBrush(Qt.black), 0.5))
                    pt.drawEllipse(translatedEll.boundingRect())
                    pt.setCompositionMode(QPainter.CompositionMode_SourceIn)
                else:
                    pt.setClipRegion(translatedEll)
                    pt.setCompositionMode(QPainter.CompositionMode_Source)
                
                pt.drawPixmap(pixmap2.rect(), self.__pixmap,
                              ell.boundingRect())
                pt.end()
                
                self.grabbed.emit(pixmap2)
        else:
            r = QRect(self.__selection)
            if not r.isNull() and r.isValid():
                self.__grabbing = True
                self.grabbed.emit(self.__pixmap.copy(r))
Exemplo n.º 35
0
class Sprite:
    def __init__(self, pos=None, sheet=None, parent=None, width=None, height=None):
        if pos is None:
            self.pos = Position(pos=[0, 0])
        else:
            self.pos = Position(pos=pos)
        self.parent = parent
        self.width = width
        self.height = height
        self.sheet = QPixmap(sheet)
        self.pix = None
        self.states = {'static':
                           {'pix'   : [],
                            'delay' : 1000}}
        self.state = 'static'
        self.step = 0

        self.delay = 50
        self.timer = QTimer()
        self.timer.timeout.connect(self.animate)
        self.timer.setInterval(self.delay)
        self.timer.start()

    def set_sheet(self, sheet):
        self.sheet = QPixmap(sheet)

    def set_static(self, pix_pos=None, x_shift=None, y_shift=None, x_offset=0, y_offset=0,
                   z=1, scale=1.0):
        if pix_pos is None:
            pix_pos = Position()
        else:
            pix_pos = Position(pos=pix_pos)
        if x_shift is None or y_shift is None:
            self.states['static']['pix'].append(self.sheet)
        else:
            self.states['static']['pix'].append(self.sheet.copy(pix_pos.x(), pix_pos.y(), x_shift, y_shift))
        self.pix = self.parent.m_scene.addPixmap(self.states['static']['pix'][0])
        self.pix.setPos(self.pos.x(), self.pos.y())
        self.pix.setOffset(x_offset, y_offset)
        self.pix.setZValue(z)
        self.pix.setScale(scale)

    def move_sprite(self, pos):
        self.pos.set(pos)
        self.pix.setPos(self.pos.x(), self.pos.y())

    def set_state(self, state):
        self.state = state
        self.timer.setInterval(self.states[state]['delay'])
        self.step = 0
        self.pix.setPixmap(self.states[state]['pix'][self.step])

    def add_state(self, name, maps=[], delay=50):
        self.states[name] = {}
        self.states[name]['pix'] = maps
        self.states[name]['delay'] = delay

    def animate(self):
        self.step += 1
        if self.step >= len(self.states[self.state]['pix']):
            self.step = 0
        #print('step:', self.step)
        self.pix.setPixmap(self.states[self.state]['pix'][self.step])
Exemplo n.º 36
0
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)

        random.seed(QCursor.pos().x() ^ QCursor.pos().y())

        self.model.addPieces(self.puzzleImage)
        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 = QListView()
        self.piecesList.setDragEnabled(True)
        self.piecesList.setViewMode(QListView.IconMode)
        self.piecesList.setIconSize(QSize(60,60))
        self.piecesList.setGridSize(QSize(80,80))
        self.piecesList.setSpacing(10)
        self.piecesList.setMovement(QListView.Snap)
        self.piecesList.setAcceptDrops(True)
        self.piecesList.setDropIndicatorShown(True)

        self.model = PiecesModel(self)
        self.piecesList.setModel(self.model)

        self.puzzleWidget = PuzzleWidget()

        self.puzzleWidget.puzzleCompleted.connect(self.setCompleted,
                Qt.QueuedConnection)

        frameLayout.addWidget(self.piecesList)
        frameLayout.addWidget(self.puzzleWidget)
        self.setCentralWidget(frame)
Exemplo n.º 37
0
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)
Exemplo n.º 38
0
class MapWidget(QWidget):

    stopSIG=pyqtSignal()
    
    def __init__(self,winParent):    
        super(MapWidget, self).__init__()
        self.winParent=winParent
        self.initUI()

        self.carx = 0.0
        self.cary = 0.0
        self.phax = 0.0
        self.phay = 0.0
        self.scale = 4.0
        self.laser = []
        
    def initUI(self):
        layout=QGridLayout()  
        #self.setLayout(layout)
        #self.setAutoFillBackground(True)
        #p = self.palette()
        #p.setColor(self.backgroundRole(), QColor('#0D488A'))
        #self.setPalette(p)
        #self.map = cv2.imread("resources/Nurburgrin800W3.png", cv2.IMREAD_GRAYSCALE)
        # cv2.imshow("@@@",self.map)
        # cv2.waitKey(0)
        #self.map = cv2.resize(self.map, (WIDTH,HEIGHT))
        #self.map = cv2.resize(self.map, (800, 668))
        # image = QImage(self.map.data, self.map.shape[1], self.map.shape[0], self.map.shape[1], QImage.Format_Indexed8);
        self.pixmap = QPixmap("resources/Nurburghrin800W3.png")
        self.mapWidget = QLabel(self)
        self.mapWidget.setPixmap(self.pixmap)
        self.resize(WIDTH,HEIGHT)
        self.setMinimumSize(WIDTH,HEIGHT)

    def RTx(self, angle, tx, ty, tz):
        RT = np.matrix([[1, 0, 0, tx], [0, math.cos(angle), -math.sin(angle), ty], [0, math.sin(angle), math.cos(angle), tz], [0,0,0,1]])
        return RT
        
    def RTy(self, angle, tx, ty, tz):
        RT = np.matrix([[math.cos(angle), 0, math.sin(angle), tx], [0, 1, 0, ty], [-math.sin(angle), 0, math.cos(angle), tz], [0,0,0,1]])
        return RT
    
    def RTz(self, angle, tx, ty, tz):
        RT = np.matrix([[math.cos(angle), -math.sin(angle), 0, tx], [math.sin(angle), math.cos(angle),0, ty], [0, 0, 1, tz], [0,0,0,1]])
        return RT 

    def drawCircle(self, painter, centerX, centerY, color, size):
        pen = QPen(color, size)
        painter.setPen(pen)
        brush = QBrush(Qt.SolidPattern)
        brush.setColor(QColor(Qt.blue))
        painter.setBrush(brush)
        painter.drawEllipse(centerX, centerY, 5, 5)

    def drawName(self, painter, posx, posy, color, size, name):
        pen = QPen(color, size)
        painter.setPen(pen)
        px1 = posx - 10
        py1 = posy - 10
        # painter.drawLine(QPointF(posx - 5,posy + 5), QPointF(px1,py1))
        # painter.drawLine(QPointF(px1,py1), QPointF(px1+10,py1))
        painter.setFont(QFont("Ubuntu Mono",12, QFont.Bold))
        painter.drawText(QPointF(px1, py1), name)

        
    def paintEvent(self, e):

        copy = self.pixmap.copy()
        painter = QPainter(copy)
        painter.translate(QPoint(self.width()/2, self.height()/2))
        RTx = self.RTx(-pi, 0, 0, 0)
        p = RTx*np.matrix([[self.carx], [self.cary], [1], [1]])
        px = p.flat[0]*self.scale
        py = p.flat[1]*self.scale        
        self.drawCircle(painter,px,py,Qt.blue,2)
        self.drawName(painter,px,py,Qt.blue,1, "F1")

        #Draw phantom
        p = RTx*np.matrix([[self.phax], [self.phay], [1], [1]])
        px = p.flat[0]*self.scale
        py = p.flat[1]*self.scale        
        self.drawCircle(painter,px,py,Qt.black,2)
        self.drawName(painter,px,py,Qt.black,1, "Pha")

        self.mapWidget.setPixmap(copy)
        painter.end()


    def drawCar(self, painter):
        carsize = 60
        tiresize = carsize/5

        pen = QPen(Qt.black, 1)
        painter.setPen(pen)

        # Connectors
        painter.drawLine(QPointF(-carsize/5,carsize/5),QPointF(carsize/5, carsize/5))

        # Chassis
        painter.fillRect(-carsize/6,carsize/2,carsize/3,carsize/2,Qt.red)
        painter.fillRect(-carsize/16,0,carsize/8,carsize,Qt.red)
        painter.fillRect(-carsize/6,-carsize/24,carsize/3,carsize/12,Qt.red)
        painter.fillRect(-carsize/8,carsize-carsize/96,carsize/4,carsize/12,Qt.red)

        # Tires
        painter.fillRect(-carsize/4,carsize/8,tiresize/2,tiresize,Qt.black)
        painter.fillRect(carsize/4,carsize/8,-tiresize/2,tiresize,Qt.black)
        painter.fillRect(-carsize/4,carsize-carsize/8,tiresize/2,tiresize,Qt.black)
        painter.fillRect(carsize/4,carsize-carsize/8,-tiresize/2,tiresize,Qt.black)


    def drawLasel(self, painter):
        pen = QPen(QColor('#6897BB'), 2)
        painter.setPen(pen)
        for d in self.laser:
            px = -d[0]*math.sin(d[1])*self.scale
            py = d[0]*math.cos(d[1])*self.scale
            painter.drawLine(QPointF(0,0),QPointF(py, px))
            
    def drawArrow(self, painter, posx, posy, color, width):
        if posx == 0.0 and posy == 0.0:
            return        

        _width = self.width()
        _height = self.height()

        pen = QPen(color, width)
        painter.setPen(pen)

        # Calculate relative coordintaes of point
        #px = _width/2*posx/10.0
        #py = _height/2*posy/10.0

        RTx = self.RTx(pi, 0, 0, 0)
        RTz = self.RTz(pi/2, 0, 0, 0)
        RT = RTx*RTz
        p = RT*np.matrix([[posx], [posy], [1], [1]])
        px = p.flat[0]*self.scale
        py = p.flat[1]*self.scale

        # Draw main line
        painter.drawLine(QPointF(0,0),QPointF(px, py))
        #print("PRE: ",posx, posy)
        #print("POST: ",px,py)

        # Draw sides
        sidex = math.hypot(px, py)/5.0
        sidey = math.hypot(px, py)/5.0
        if px != 0.0:
            ang = math.atan2(py,px)
        else:
            ang = math.pi/2.0
        if posx >= 0.0:
            px1 = px + sidex * math.cos(math.pi+ang-0.5)
            py1 = py + sidey * math.sin(math.pi+ang-0.5)
            px2 = px + sidex * math.cos(math.pi+ang+0.5)
            py2 = py + sidey * math.sin(math.pi+ang+0.5)
        else:
            px1 = px - sidex * math.cos(ang-0.5)
            py1 = py - sidey * math.sin(ang-0.5)
            px2 = px - sidex * math.cos(ang+0.5)
            py2 = py - sidey * math.sin(ang+0.5)    
        painter.drawLine(QPointF(px, py),QPointF(px1, py1))
        painter.drawLine(QPointF(px, py),QPointF(px2, py2))

        #print(px,py)
        #print(px1,py1)

    def drawTarget(self, painter, posx, posy):

        if posx == 0.0 and posy == 0.0:
            return        

        pen = QPen(Qt.yellow, 4)
        painter.setPen(pen)

        sx = posx - 0.25
        sy = posy - 0.25
        ex = posx + 0.25
        ey = posy + 0.25
        painter.drawLine(QPointF(-sx*self.scale,sy*self.scale),QPointF(-ex*self.scale,ey*self.scale))
        painter.drawText( QPoint(-sx*self.scale+3,sy*self.scale), self.targetid );


        sx = posx + 0.25
        sy = posy - 0.25
        ex = posx - 0.25
        ey = posy + 0.25
        painter.drawLine(QPointF(-sx*self.scale,sy*self.scale),QPointF(-ex*self.scale,ey*self.scale))

    def setCarPos(self, x, y):
        self.carx = x
        self.cary = y

    def setPhantomPos(self, x, y):
        self.phax = x
        self.phay = y

    def setLaserValues(self, laser):
        # Init laser array
        if len(self.laser) == 0:
            for i in range(laser.numLaser):
                self.laser.append((0,0))

        for i in range(laser.numLaser):
            dist = laser.distanceData[i]/1000.0
            angle = math.radians(i)
            self.laser[i] = (dist, angle)