def __paint_image_array( self, raw_data, painter: "QPainter", option: "QStyleOptionViewItem", index: "QModelIndex", ): """Paints a pixmap centered on the cell. Generated pixmaps are saved on cache by the name "dataset_row_col" """ # Load Qt pixap from array pix = QPixmap() pix_name = str(id(raw_data)) if not QPixmapCache.find(pix_name, pix): # Load pix from raw array pix = QPixmap.fromImage(qimage2ndarray.array2qimage(raw_data)) # Save pix on cache QPixmapCache.insert(pix_name, pix) pix = pix.scaled(option.rect.width(), option.rect.height(), Qt.KeepAspectRatio) # Calculate central position x_coord = option.rect.center().x() - pix.width() / 2 y_coord = option.rect.center().y() - pix.height() / 2 draw_rect = QRect(x_coord, y_coord, pix.width(), pix.height()) # Draw pixm painter.drawPixmap(draw_rect, pix)
class BackgroundPainter(BasePainter): def __init__(self, parent): BasePainter.__init__(self, parent) self._galaxy = QPixmap(IMAGE_GALAXY_PATH) if self._galaxy.size() != QSize(PartyConst.WIDTH, PartyConst.HEIGHT): self._galaxy = QPixmap(QSize(PartyConst.WIDTH, PartyConst.HEIGHT)) self._galaxy.fill(QColor('#20124d')) else: self.is_set = True def setup(self): if not self.is_set: _edge = max([PartyConst.WIDTH, PartyConst.HEIGHT]) self._stars = np.random.randint(low=0, high=_edge, size=((_edge // 250)**2, 2)) self._pen_link = QPen(QColor('#351c75'), 2, Qt.SolidLine) self._lines = [] min_dist = 100 for _star in self._stars: for _sub_star in self._stars: if 0 < np.linalg.norm(_star - _sub_star) < min_dist: self._lines.append((_star, _sub_star)) _edge = max([PartyConst.WIDTH, PartyConst.HEIGHT]) _center = QPoint(self._galaxy.width() // 2, self._galaxy.height() // 2) _gradient = QRadialGradient(_center, _edge // 2) _gradient.setColorAt(1, QColor('#20124d')) _gradient.setColorAt(0, QColor('#351c75')) painter = QPainter(self._galaxy) painter.fillRect(0, 0, _edge, _edge, _gradient) painter.setPen(self._pen_link) for _xy1, _xy2 in self._lines: _xy1, _xy2 = QPoint(*_xy1), QPoint(*_xy2) painter.drawLine(_xy1, _xy2) _star_pens = [ QPen(QColor('#ffffff'), _size, Qt.SolidLine) for _size in [1, 2, 3, 4] ] for _i, (_x, _y) in enumerate(self._stars): _xy = QPoint(_x, _y) painter.setPen(_star_pens[_i % len(_star_pens)]) painter.drawPoint(_xy) painter.end() self._galaxy.save(IMAGE_GALAXY_PATH) self.is_set = True def paint(self, painter: QPainter, model: BaseModel = None): _xy = self.transform(-self._galaxy.width() // 2, self._galaxy.height() // 2, is_point=True) painter.drawPixmap(_xy, self._galaxy)
def scale_picture(self, picture: QPixmap): max_W = self.picture_holder.maximumWidth() max_H = self.picture_holder.maximumHeight() if picture.height() > max_H or picture.width() > max_W: return picture.scaled(max_W, max_H, Qt.KeepAspectRatio) else: return picture
def axis_tool(self): w = 300 h = 600 # 判断 if self.tool_dialog == None: # 创建坐标工具窗 self.tool_dialog = QDialog(self.ui) self.tool_dialog.setWindowTitle('坐标工具') self.tool_dialog.resize(w, h) # 截图 photo_path = self.screen_cap() if photo_path != None: if self.screen_cap_file != None: os.remove(self.screen_cap_file) self.screen_cap_file = photo_path pix = QPixmap(photo_path) w = pix.width() h = pix.height() # 设置面板大小 self.tool_dialog.setFixedSize(w / 4, h / 4) # 调色板 palette = QPalette() # 缩小图片 pix = pix.scaled(w / 4, h / 4) palette.setBrush(self.tool_dialog.backgroundRole(), QBrush(pix)) self.tool_dialog.setAutoFillBackground(True) self.tool_dialog.setPalette(palette) self.tool_dialog.setMouseTracking(True) # 绑定鼠标移动事件 self.tool_dialog.mouseMoveEvent = self.mouse_move # 显示窗口 self.tool_dialog.show() # 十字光标 self.tool_dialog.setCursor(Qt.CrossCursor)
def createBoard(self): dict = self.ui.comboBox_dict.currentIndex() numX = int(self.ui.lineEdit_numX.text()) numY = int(self.ui.lineEdit_numY.text()) squareSize = float(self.ui.lineEdit_squareSize.text()) dpi = int(self.ui.lineEdit_DPI.text()) imgSize = (float(self.ui.lineEdit_printX.text()), float(self.ui.lineEdit_printY.text())) if dict == 0: self.boardType = 0 self.calibBoard = ChessBoard.ChessBoard() self.board = self.calibBoard.create((numX, numY), squareSize, dpi, imgSize) # Create Board else: self.boardType = 1 self.calibBoard = CharucoBoard.CharucoBoard() self.board = self.calibBoard.create(numX, numY, dict - 1, squareSize, imgSize, dpi) #Create Board if self.board is None: ## splite Qt segment self.ui.label.setText("Create Failed,Please confire parameter!") return # showBoard image = QImage(self.board[:], self.board.shape[1], self.board.shape[0], self.board.shape[1], QImage.Format_Grayscale8) #ndarray -> QImage showBoard = QPixmap(image) #QImage -> Qpixmap if showBoard.width() > showBoard.height(): #resize Qpixmap showBoard = showBoard.scaledToWidth(self.ui.label.width()) else: showBoard = showBoard.scaledToHeight(self.ui.label.height()) self.ui.label.setPixmap(showBoard) #show
def _makeImage(self, response, maxWidth=700, maxHeight=700): # Makes an image for the given response # if response.headers['Content-Type'] == 'image/gif': # byteArray = QByteArray(response.content) # buffer = QBuffer(byteArray) # buffer.open(QIODevice.ReadOnly) # mov = QMovie(buffer, b'GIF') # mov.setCacheMode(QMovie.CacheAll) # mov.setSpeed(100) # return mov pixmap = QPixmap() pixmap.loadFromData(response.content) width, height = pixmap.width(), pixmap.height() if width > height and width > maxWidth: dx = maxWidth / width width = min(width, maxWidth) height *= dx elif height > width and height > maxHeight: dy = maxHeight / height height = min(height, maxHeight) width *= dy elif height == width: width = height = maxWidth scaled = pixmap.scaled(width, height, transformMode=Qt.SmoothTransformation) return scaled
def load_picture(self): pixmap = QPixmap(self.file_name[0]) if pixmap.width() > pixmap.height(): self.picture_label.setPixmap( pixmap.scaledToWidth(self.picture_label.width())) else: self.picture_label.setPixmap( pixmap.scaledToHeight(self.picture_label.height()))
def load_image(self, frame): height, width, channel = frame.shape bytesPerLine = 3 * width qImg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped() pixmap = QPixmap().fromImage(qImg) # print(pixmap) self.scene.addPixmap(pixmap) self.view.fitInView(QRectF(0, 0, pixmap.width(), pixmap.height()), Qt.KeepAspectRatio) self.scene.update()
def paint_with_opacity(pixmap: QPixmap, opacity: float): transparent_image = QImage(QSize(36, 36), QImage.Format_ARGB32_Premultiplied) transparent_image.fill(Qt.transparent) painter = QPainter(transparent_image) painter.setOpacity(opacity) painter.drawPixmap(18 - pixmap.width() / 2, 18 - pixmap.height() / 2, pixmap) painter.end() return QPixmap.fromImage(transparent_image)
def showImg(self, index): if self.cacheDir == '': return currentImg = QPixmap(self.cacheDir + '/marked_' + self.model.item(index.row(), 0).text()) if currentImg.width() > currentImg.height(): currentImg = currentImg.scaledToWidth(self.ui.label_show.width()) else: currentImg = currentImg.scaledToHeight(self.ui.label_show.height()) self.ui.label_show.setPixmap(currentImg)
def sizeHint(self, option, index): """ Returns the size needed to display the item in a QSize object. """ imagen = QPixmap() try: imagen.loadFromData(index.data()) # , Qt.DisplayRole except TypeError: return QStyledItemDelegate.sizeHint(self, option, index) + QSize( 1, 1) size_hint = QSize(5 * imagen.width(), imagen.height()) + QSize(1, 1) return size_hint
def dropEvent(self, event): pix = QPixmap(event.text()) print("2222",event.text()) print(self.scene()) pix = pix.scaled(pix.width() * self.ratio_w, pix.height() * self.ratio_h) matitem = ReGraphicsPixmapItem() # 创建像素图元 matitem.setPixmap(pix) matitem.setFlags( ReGraphicsPixmapItem.ItemIsMovable | ReGraphicsPixmapItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable) # self.scene.addItem(matitem) self.scene().addItem(matitem)
def _set_image(self, index): if index > len( self._all_images) - 1 or index < -1 * len(self._all_images): l.log("error: resetting again") index = 0 self._current_index = index l.log("setting image") image_pix_map = QPixmap(self._all_images[self._current_index]) print("image: ", image_pix_map.width(), image_pix_map.height()) self._image_label.setPixmap(image_pix_map) self.set_title(self._all_images[self._current_index])
def addBackground(self): scene = self.scene() if not DisplayOptions.map_poly: bg = QPixmap("./resources/" + self.game.theater.overview_image) scene.addPixmap(bg) # Apply graphical effects to simulate current daytime if self.game.current_turn_time_of_day == TimeOfDay.Day: pass elif self.game.current_turn_time_of_day == TimeOfDay.Night: ov = QPixmap(bg.width(), bg.height()) ov.fill(CONST.COLORS["night_overlay"]) overlay = scene.addPixmap(ov) effect = QGraphicsOpacityEffect() effect.setOpacity(0.7) overlay.setGraphicsEffect(effect) else: ov = QPixmap(bg.width(), bg.height()) ov.fill(CONST.COLORS["dawn_dust_overlay"]) overlay = scene.addPixmap(ov) effect = QGraphicsOpacityEffect() effect.setOpacity(0.3) overlay.setGraphicsEffect(effect) else: # Polygon display mode if self.game.theater.landmap is not None: for sea_zone in self.game.theater.landmap[2]: print(sea_zone) poly = QPolygonF([QPointF(*self._transform_point(Point(point[0], point[1]))) for point in sea_zone]) scene.addPolygon(poly, CONST.COLORS["sea_blue"], CONST.COLORS["sea_blue"]) for inclusion_zone in self.game.theater.landmap[0]: poly = QPolygonF([QPointF(*self._transform_point(Point(point[0], point[1]))) for point in inclusion_zone]) scene.addPolygon(poly, CONST.COLORS["grey"], CONST.COLORS["dark_grey"]) for exclusion_zone in self.game.theater.landmap[1]: poly = QPolygonF([QPointF(*self._transform_point(Point(point[0], point[1]))) for point in exclusion_zone]) scene.addPolygon(poly, CONST.COLORS["grey"], CONST.COLORS["dark_dark_grey"])
def drawGrid(self, image): "draws a grid on image" img = QPixmap(image.width() + 1, image.height() + 1) p = QPainter(img) p.drawPixmap(1, 1, image) # the +1 is for the grid around the image; otherwise grid is cut off w, h, z = img.width(), img.height(), self.zoom for i in range(max(self.width, self.height) + 1): p.drawLine(QPoint(0, i * z), QPoint(w, i * z)) # horiztonal lines p.drawLine(QPoint(i * z, 0), QPoint(i * z, h)) # vertical lines return img
def initStyleOption(self, option: QStyleOptionViewItem, index: QModelIndex): super().initStyleOption(option, index) if index.siblingAtRow(index.row() + 1).isValid(): # If we have a color, show it as decoration. Otherwise, show a cross. pixmap = QPixmap(option.decorationSize) color = index.data(Qt.DecorationRole) if color: pixmap.fill(color) else: pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.drawLine(0, 0, pixmap.width() - 1, pixmap.height() - 1) painter.drawLine(0, pixmap.height() - 1, pixmap.width() - 1, 0) painter.end() option.icon = QIcon(pixmap) # Always show the decoration option.features |= QStyleOptionViewItem.HasDecoration else: option.features &= ~QStyleOptionViewItem.HasDecoration
def __init__(self, pointEditor: PointEditor, image: QtGui.QPixmap, parent=None): self.pointEditor = pointEditor self.image = image if image: imw = image.width() imh = image.height() pointEditor.xValSpin.setMaximum(imw) pointEditor.xValSpin.setMinimum(0) pointEditor.yValSpin.setMaximum(imh) pointEditor.yValSpin.setMinimum(0) super().__init__(parent)
def addBackground(self): scene = self.scene() bg = QPixmap("./resources/" + self.game.theater.overview_image) scene.addPixmap(bg) # Apply graphical effects to simulate current daytime if self.game.current_turn_daytime == "day": pass elif self.game.current_turn_daytime == "night": ov = QPixmap(bg.width(), bg.height()) ov.fill(CONST.COLORS["night_overlay"]) overlay = scene.addPixmap(ov) effect = QGraphicsOpacityEffect() effect.setOpacity(0.7) overlay.setGraphicsEffect(effect) else: ov = QPixmap(bg.width(), bg.height()) ov.fill(CONST.COLORS["dawn_dust_overlay"]) overlay = scene.addPixmap(ov) effect = QGraphicsOpacityEffect() effect.setOpacity(0.3) overlay.setGraphicsEffect(effect)
def load_image(self, image_arr): self.clear() image_path = QImage(image_arr, image_arr.shape[1], image_arr.shape[0], QImage.Format_RGB888) pixmap = QPixmap(image_path) self.scene.addPixmap(pixmap) self.img_width = pixmap.width() self.img_height = pixmap.height() self.scale_self() self.scene.update()
def createDropTextPixmap(self): pixmap = QPixmap(481, 300) pixmap.fill(QColor("#333333")) painter = QPainter(pixmap) font = QFont("Arial") font.setPixelSize(28) font.setBold(True) fm = QFontMetrics(font) painter.setFont(font) painter.setPen(QPen(QColor("#888888"), 1)) text = "Drop the tileset image here" x = (pixmap.width()-fm.width(text))/2 y = (pixmap.height()+fm.height())/2 painter.drawText(x, y, text) del painter return pixmap
def paint(self, painter, option, index): """ Paint the items in the table. If the item referred to by <index> is a StarRating, we handle the painting ourselves. For the other items, we let the base class handle the painting as usual. In a polished application, we'd use a better check than the column number to find out if we needed to paint the stars, but it works for the purposes of this example. """ if option.state & QStyle.State_Enabled: if option.state & QStyle.State_Active: color_group = QPalette.Normal else: color_group = QPalette.Inactive else: color_group = QPalette.Disabled if option.state & QStyle.State_Selected: painter.fillRect( option.rect, option.palette.color(color_group, QPalette.Highlight)) imagen = QPixmap() try: imagen.loadFromData(index.data()) # , Qt.DisplayRole except TypeError: return QStyledItemDelegate.paint(self, painter, option, index) imagen = imagen.scaled(QSize(16, 16), Qt.KeepAspectRatio) width = imagen.width() height = imagen.height() """Para calcular el lugar donde se tiene que dibujar 1. option.rect te da: (0, 0, width() , height() ) of the image 2. Del punto en el que hay que empezar a dibujar, le sumamos la mitad del ancho de la celda 3. Y luego le restamos el ancho del objeto para que quede en la mitad """ x = option.rect.x() + (option.rect.width() / 2) - (width / 2) y = option.rect.y() + (option.rect.height() / 2) - (height / 2) # x,y cordenadas - 32,32 ancho y alto de la imagen - la imagen painter.drawPixmap(x, y, imagen) pen = painter.pen() painter.setPen(option.palette.color(QPalette.Mid))
def resizeImage(self, filename): pixmap = QPixmap(filename) lwidth = self.label.maximumWidth() pwidth = pixmap.width() lheight = self.label.maximumHeight() pheight = pixmap.height() wratio = pwidth * 1.0 / lwidth hratio = pheight * 1.0 / lheight if pwidth > lwidth or pheight > lheight: if wratio > hratio: lheight = pheight / wratio else: lwidth = pwidth / hratio scaled_pixmap = pixmap.scaled(lwidth, lheight) return scaled_pixmap else: return pixmap
def paintEvent(self, a0: QtGui.QPaintEvent) -> None: """ 重载paintEvent函数 :param a0: :return: """ p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) p.save() p.setPen(Qt.NoPen) lgt = QLinearGradient(QPointF(0, 0), QPointF(self.width(), 0)) lgt.setColorAt(0.0, QColor('#511235')) lgt.setColorAt(1.0, QColor('red')) p.setBrush(lgt) p.drawRect(QRectF(0, 0, self.width(), self._m_title_height)) p.drawRect( QRectF(0, self.height() - self._m_status_label.height(), self.rect().width(), self._m_status_label.height())) line_pen = QPen() line_pen.setColor(QColor(30, 144, 255, 30)) line_pen.setWidth(1) p.setPen(line_pen) p.drawLine(0, self.rect().height() - self._m_status_label.height(), self.rect().width(), self.rect().height() - self._m_status_label.height()) # 在窗口左上角画图标 if self._m_icon_path: imx = QPixmap(self._m_icon_path) p.drawPixmap(5, (self._m_title_label.height() - imx.height()) / 2, imx) p.restore()
def addPerson(self, pos, angle=0, color=-1, size=100): colors = QColor.colorNames() color = colors[random.randint(0, len(colors) - 1)] if color == -1 else color pos = [pos[0], pos[2]] if len(pos) > 2 else pos p = self.scene.addEllipse(pos[0] - size // 2, pos[1] - size // 2, size, size, pen=QPen(QColor(color), 20), brush=QBrush(color=QColor(color))) # pixmap pixmap = QPixmap("person.png").scaled(600, 300) self.pixmapSize = (pixmap.width() / 2, pixmap.height() / 2) pixItem = QGraphicsPixmapItem(pixmap) pixItem.setTransformOriginPoint(pixItem.boundingRect().center()) pixItem.setZValue(20) self.scene.addItem(pixItem) self.persons[p] = pixItem return p
def testQPixmapConstructor(self): label = QLabel() pixmap1 = QPixmap(xpm) self.assertFalse(pixmap1.isNull()) self.assertEqual(pixmap1.width(), 27) self.assertEqual(pixmap1.height(), 22)
class QtImg(QtWidgets.QWidget): def __init__(self): super(self.__class__, self).__init__() self.bookId = "" self.epsId = 0 self.curIndex = 0 self.gridLayout = QtWidgets.QGridLayout(self) self.setWindowTitle("图片查看") self.setWindowModality(QtCore.Qt.ApplicationModal) self.resize(402, 509) # self.setWindowFlags(Qt.FramelessWindowHint) self.graphicsView = QtWidgets.QGraphicsView(self) self.graphicsView.setFrameStyle(QFrame.NoFrame) self.graphicsView.setObjectName("graphicsView") self.graphicsView.setBackgroundBrush(QColor(Qt.white)) self.graphicsView.setCursor(Qt.OpenHandCursor) self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphicsView.setRenderHints(QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform) self.graphicsView.setCacheMode(self.graphicsView.CacheBackground) self.graphicsView.setViewportUpdateMode( self.graphicsView.SmartViewportUpdate) self.graphicsItem = QGraphicsPixmapItem() self.graphicsItem.setFlags(QGraphicsPixmapItem.ItemIsFocusable | QGraphicsPixmapItem.ItemIsMovable) self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.CopyPicture) self.graphicsScene = QGraphicsScene(self) # 场景 self.graphicsView.setScene(self.graphicsScene) self.graphicsScene.addItem(self.graphicsItem) self.graphicsView.setMinimumSize(10, 10) self.pixMap = QPixmap("加载中") self.graphicsItem.setPixmap(self.pixMap) # self.radioButton.setChecked(True) self.isStripModel = False # self.radioButton.installEventFilter(self) # self.radioButton_2.installEventFilter(self) self.graphicsView.installEventFilter(self) self.graphicsView.setWindowFlag(Qt.FramelessWindowHint) self.gridLayout.addWidget(self.graphicsView) self._delta = 0.1 self.scaleCnt = 0 def ShowImg(self, pixMap): self.scaleCnt = 0 self.pixMap = QPixmap(pixMap) self.show() self.graphicsItem.setPixmap(self.pixMap) self.graphicsView.setSceneRect( QRectF(QPointF(0, 0), QPointF(self.pixMap.width(), self.pixMap.height()))) self.ScalePicture() def ScalePicture(self): rect = QRectF(self.graphicsItem.pos(), QSizeF(self.pixMap.size())) unity = self.graphicsView.transform().mapRect(QRectF(0, 0, 1, 1)) width = unity.width() height = unity.height() if width <= 0 or height <= 0: return self.graphicsView.scale(1 / width, 1 / height) viewRect = self.graphicsView.viewport().rect() sceneRect = self.graphicsView.transform().mapRect(rect) if sceneRect.width() <= 0 or sceneRect.height() <= 0: return x_ratio = viewRect.width() / sceneRect.width() y_ratio = viewRect.height() / sceneRect.height() x_ratio = y_ratio = min(x_ratio, y_ratio) self.graphicsView.scale(x_ratio, y_ratio) # if self.readImg.isStripModel: # height2 = self.pixMap.size().height() / 2 # height3 = self.graphicsView.size().height()/2 # height3 = height3/x_ratio # p = self.graphicsItem.pos() # self.graphicsItem.setPos(p.x(), p.y()+height2-height3) self.graphicsView.centerOn(rect.center()) for _ in range(abs(self.scaleCnt)): if self.scaleCnt > 0: self.graphicsView.scale(1.1, 1.1) else: self.graphicsView.scale(1 / 1.1, 1 / 1.1) def resizeEvent(self, event) -> None: super(self.__class__, self).resizeEvent(event) self.ScalePicture() def eventFilter(self, obj, ev): if ev.type() == QEvent.KeyPress: return True else: return super(self.__class__, self).eventFilter(obj, ev) def wheelEvent(self, event): if event.angleDelta().y() > 0: self.zoomIn() else: self.zoomOut() def zoomIn(self): """放大""" self.zoom(1.1) def zoomOut(self): """缩小""" self.zoom(1 / 1.1) def zoom(self, factor): """缩放 :param factor: 缩放的比例因子 """ _factor = self.graphicsView.transform().scale(factor, factor).mapRect( QRectF(0, 0, 1, 1)).width() if _factor < 0.07 or _factor > 100: # 防止过大过小 return if factor >= 1: self.scaleCnt += 1 else: self.scaleCnt -= 1 self.graphicsView.scale(factor, factor) def CopyPicture(self): clipboard = QApplication.clipboard() clipboard.setPixmap(self.pixMap) QtBubbleLabel.ShowMsgEx(self, "复制成功") return
class BookDelegate(QSqlRelationalDelegate): """Books delegate to rate the books""" def __init__(self, parent=None): QSqlRelationalDelegate.__init__(self, parent) self.star = QPixmap(os.path.join(__file__,"..","images","star.png")) def paint(self, painter, option, index): """ Paint the items in the table. If the item referred to by <index> is a StarRating, we handle the painting ourselves. For the other items, we let the base class handle the painting as usual. In a polished application, we'd use a better check than the column number to find out if we needed to paint the stars, but it works for the purposes of this example. """ if index.column() != 5: # Since we draw the grid ourselves: opt = copy.copy(option) opt.rect = option.rect.adjusted(0, 0, -1, -1) QSqlRelationalDelegate.paint(self, painter, opt, index) else: model = index.model() if option.state & QStyle.State_Enabled: if option.state & QStyle.State_Active: color_group = QPalette.Normal else: color_group = QPalette.Inactive else: color_group = QPalette.Disabled if option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.color(color_group, QPalette.Highlight)) rating = model.data(index, Qt.DisplayRole) width = self.star.width() height = self.star.height() x = option.rect.x() y = option.rect.y() + (option.rect.height() / 2) - (height / 2) for i in range(rating): painter.drawPixmap(x, y, self.star) x += width # Since we draw the grid ourselves: self.drawFocus(painter, option, option.rect.adjusted(0, 0, -1, -1)) pen = painter.pen() painter.setPen(option.palette.color(QPalette.Mid)) painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) painter.drawLine(option.rect.topRight(), option.rect.bottomRight()) painter.setPen(pen) def sizeHint(self, option, index): """ Returns the size needed to display the item in a QSize object. """ if index.column() == 5: size_hint = QSize(5 * self.star.width(), self.star.height()) + QSize(1, 1) return size_hint # Since we draw the grid ourselves: return QSqlRelationalDelegate.sizeHint(self, option, index) + QSize(1, 1) def editorEvent(self, event, model, option, index): if index.column() != 5: return False if event.type() == QEvent.MouseButtonPress: mouse_pos = event.pos() new_stars = int(0.7 + (mouse_pos.x() - option.rect.x()) / self.star.width()) stars = max(0, min(new_stars, 5)) model.setData(index, stars) # So that the selection can change return False return True def createEditor(self, parent, option, index): if index.column() != 4: return QSqlRelationalDelegate.createEditor(self, parent, option, index) # For editing the year, return a spinbox with a range from -1000 to 2100. spinbox = QSpinBox(parent) spinbox.setFrame(False) spinbox.setMaximum(2100) spinbox.setMinimum(-1000) return spinbox
def addBackground(self): scene = self.scene() if not DisplayOptions.map_poly: bg = QPixmap("./resources/" + self.game.theater.overview_image) scene.addPixmap(bg) # Apply graphical effects to simulate current daytime if self.game.current_turn_time_of_day == TimeOfDay.Day: pass elif self.game.current_turn_time_of_day == TimeOfDay.Night: ov = QPixmap(bg.width(), bg.height()) ov.fill(CONST.COLORS["night_overlay"]) overlay = scene.addPixmap(ov) effect = QGraphicsOpacityEffect() effect.setOpacity(0.7) overlay.setGraphicsEffect(effect) else: ov = QPixmap(bg.width(), bg.height()) ov.fill(CONST.COLORS["dawn_dust_overlay"]) overlay = scene.addPixmap(ov) effect = QGraphicsOpacityEffect() effect.setOpacity(0.3) overlay.setGraphicsEffect(effect) if DisplayOptions.map_poly or self.reference_point_setup_mode: # Polygon display mode if self.game.theater.landmap is not None: for sea_zone in self.game.theater.landmap.sea_zones: print(sea_zone) poly = QPolygonF([ QPointF( *self._transform_point(Point(point[0], point[1]))) for point in sea_zone.exterior.coords ]) if self.reference_point_setup_mode: color = "sea_blue_transparent" else: color = "sea_blue" scene.addPolygon(poly, CONST.COLORS[color], CONST.COLORS[color]) for inclusion_zone in self.game.theater.landmap.inclusion_zones: poly = QPolygonF([ QPointF( *self._transform_point(Point(point[0], point[1]))) for point in inclusion_zone.exterior.coords ]) if self.reference_point_setup_mode: scene.addPolygon(poly, CONST.COLORS["grey_transparent"], CONST.COLORS["dark_grey_transparent"]) else: scene.addPolygon(poly, CONST.COLORS["grey"], CONST.COLORS["dark_grey"]) for exclusion_zone in self.game.theater.landmap.exclusion_zones: poly = QPolygonF([ QPointF( *self._transform_point(Point(point[0], point[1]))) for point in exclusion_zone.exterior.coords ]) if self.reference_point_setup_mode: scene.addPolygon( poly, CONST.COLORS["grey_transparent"], CONST.COLORS["dark_dark_grey_transparent"]) else: scene.addPolygon(poly, CONST.COLORS["grey"], CONST.COLORS["dark_dark_grey"]) # Uncomment to display plan projection test # self.projection_test() self.draw_scale() if self.reference_point_setup_mode: for i, point in enumerate(self.game.theater.reference_points): self.scene().addRect(QRectF(point.image_coordinates.x, point.image_coordinates.y, 25, 25), pen=CONST.COLORS["red"], brush=CONST.COLORS["red"]) text = self.scene().addText( f"P{i} = {point.image_coordinates}", font=QFont("Trebuchet MS", 14, weight=8, italic=False)) text.setDefaultTextColor(CONST.COLORS["red"]) text.setPos(point.image_coordinates.x + 26, point.image_coordinates.y) # Set to True to visually debug _transform_point. draw_transformed = False if draw_transformed: x, y = self._transform_point(point.world_coordinates) self.scene().addRect(QRectF(x, y, 25, 25), pen=CONST.COLORS["red"], brush=CONST.COLORS["red"]) text = self.scene().addText(f"P{i}' = {x}, {y}", font=QFont("Trebuchet MS", 14, weight=8, italic=False)) text.setDefaultTextColor(CONST.COLORS["red"]) text.setPos(x + 26, y)
class Window(QWidget): def __init__(self): # call the constructor of the parent (QWidget) super().__init__() # check if it the first time for user to plot self.firstTime = False # set title for the window self.setWindowTitle("Smart Schematic") # add the schematic to the widget and center it self.label = QLabel(self) self.pixmap = QPixmap('schematic.png') self.pixmap = self.pixmap.scaled(self.pixmap.width() * 0.7, self.pixmap.height() * 0.7, Qt.KeepAspectRatio) self.label.setPixmap(self.pixmap) self.label.setScaledContents(True) self.resize(self.pixmap.width(), self.pixmap.height()) # set minimum width and height for the window to fit the image self.setMinimumHeight(self.pixmap.height()) self.setMinimumWidth(self.pixmap.width()) self.setMaximumHeight(self.pixmap.height()) self.setMaximumWidth(self.pixmap.width()) # set icon for the application at run time and center the application window with the primary screen self.setIcon() self.center() # add default transistors label for the schematic self.setTransistorsLabels() # add default components label for the schematic self.setVoltageLabels() self.setCurrentLabels() # add all transistors label at the start above the schematic def setTransistorsLabels(self): # set default font for all transistors label font = QFont("SansSerif", 14, italic=True) # set all transistors label self.trans1a = QLabel(self.label) self.trans1a.setText("M1a") self.trans1a.move(282, 243) self.trans1a.setFont(font) self.trans2a = QLabel(self.label) self.trans2a.setText("M2a") self.trans2a.move(77, 368) self.trans2a.setFont(font) self.trans3a = QLabel(self.label) self.trans3a.setText("M3a") self.trans3a.move(77, 288) self.trans3a.setFont(font) self.trans4a = QLabel(self.label) self.trans4a.setText("M4a") self.trans4a.move(77, 178) self.trans4a.setFont(font) self.trans5a = QLabel(self.label) self.trans5a.setText("M5a") self.trans5a.move(77, 110) self.trans5a.setFont(font) self.trans1b = QLabel(self.label) self.trans1b.setText("M1b") self.trans1b.move(337, 243) self.trans1b.setFont(font) self.trans2b = QLabel(self.label) self.trans2b.setText("M2b") self.trans2b.move(545, 368) self.trans2b.setFont(font) self.trans3b = QLabel(self.label) self.trans3b.setText("M3b") self.trans3b.move(545, 288) self.trans3b.setFont(font) self.trans4b = QLabel(self.label) self.trans4b.setText("M4b") self.trans4b.move(545, 178) self.trans4b.setFont(font) self.trans5b = QLabel(self.label) self.trans5b.setText("M5b") self.trans5b.move(545, 110) self.trans5b.setFont(font) self.trans6 = QLabel(self.label) self.trans6.setText("M6") self.trans6.move(337, 150) self.trans6.setFont(font) self.colorDefaultLabels() # color all transistors with blue def colorDefaultLabels(self): self.trans1a.setStyleSheet("color: blue") self.trans2a.setStyleSheet("color: blue") self.trans3a.setStyleSheet("color: blue") self.trans4a.setStyleSheet("color: blue") self.trans5a.setStyleSheet("color: blue") self.trans1b.setStyleSheet("color: blue") self.trans2b.setStyleSheet("color: blue") self.trans3b.setStyleSheet("color: blue") self.trans4b.setStyleSheet("color: blue") self.trans5b.setStyleSheet("color: blue") self.trans6.setStyleSheet("color: blue") def setVoltageLabels(self): # set default fonts for all components label font1 = QFont("SansSerif", 14, italic=True) font2 = QFont("SansSerif", 11, italic=True) label1 = QLabel(self.label) label1.setText("V") label1.move(182, 290) label1.setFont(font1) label1.setStyleSheet("color: blue") label2 = QLabel(self.label) label2.setText("cascn") label2.move(195, 297) label2.setFont(font2) label2.setStyleSheet("color: blue") label3 = QLabel(self.label) label3.setText("V") label3.move(182, 245) label3.setFont(font1) label3.setStyleSheet("color: blue") label4 = QLabel(self.label) label4.setText("in+") label4.move(195, 253) label4.setFont(font2) label4.setStyleSheet("color: blue") label5 = QLabel(self.label) label5.setText("V") label5.move(35, 232) label5.setFont(font1) label5.setStyleSheet("color: blue") label6 = QLabel(self.label) label6.setText("out-") label6.move(48, 240) label6.setFont(font2) label6.setStyleSheet("color: blue") label7 = QLabel(self.label) label7.setText("V") label7.move(182, 175) label7.setFont(font1) label7.setStyleSheet("color: blue") label8 = QLabel(self.label) label8.setText("cascp") label8.move(195, 183) label8.setFont(font2) label8.setStyleSheet("color: blue") label9 = QLabel(self.label) label9.setText("V") label9.move(220, 150) label9.setFont(font1) label9.setStyleSheet("color: blue") label10 = QLabel(self.label) label10.setText("cmfp") label10.move(233, 158) label10.setFont(font2) label10.setStyleSheet("color: blue") label11 = QLabel(self.label) label11.setText("V") label11.move(215, 90) label11.setFont(font1) label11.setStyleSheet("color: blue") label12 = QLabel(self.label) label12.setText("biasp") label12.move(228, 98) label12.setFont(font2) label12.setStyleSheet("color: blue") label13 = QLabel(self.label) label13.setText("V") label13.move(420, 290) label13.setFont(font1) label13.setStyleSheet("color: blue") label14 = QLabel(self.label) label14.setText("cascn") label14.move(433, 297) label14.setFont(font2) label14.setStyleSheet("color: blue") label15 = QLabel(self.label) label15.setText("V") label15.move(441, 245) label15.setFont(font1) label15.setStyleSheet("color: blue") label16 = QLabel(self.label) label16.setText("in-") label16.move(454, 253) label16.setFont(font2) label16.setStyleSheet("color: blue") label17 = QLabel(self.label) label17.setText("V") label17.move(420, 175) label17.setFont(font1) label17.setStyleSheet("color: blue") label18 = QLabel(self.label) label18.setText("cascp") label18.move(433, 183) label18.setFont(font2) label18.setStyleSheet("color: blue") label19 = QLabel(self.label) label19.setText("V") label19.move(577, 232) label19.setFont(font1) label19.setStyleSheet("color: blue") label20 = QLabel(self.label) label20.setText("out+") label20.move(590, 240) label20.setFont(font2) label20.setStyleSheet("color: blue") label21 = QLabel(self.label) label21.setText("V") label21.move(310, 320) label21.setFont(font1) label21.setStyleSheet("color: blue") label22 = QLabel(self.label) label22.setText("biasn") label22.move(323, 327) label22.setFont(font2) label22.setStyleSheet("color: blue") label23 = QLabel(self.label) label23.setText("V") label23.move(310, 37) label23.setFont(font1) label23.setStyleSheet("color: blue") label24 = QLabel(self.label) label24.setText("DD") label24.move(323, 45) label24.setFont(font2) label24.setStyleSheet("color: blue") def setCurrentLabels(self): # set default fonts for all components label font1 = QFont("SansSerif", 11, italic=True) font2 = QFont("SansSerif", 9, italic=True) label1 = QLabel(self.label) label1.setText("I") label1.move(235, 207) label1.setFont(font1) label1.setStyleSheet("color: blue") label2 = QLabel(self.label) label2.setText("bias") label2.move(240, 215) label2.setFont(font2) label2.setStyleSheet("color: blue") label3 = QLabel(self.label) label3.setText("I") label3.move(392, 207) label3.setFont(font1) label3.setStyleSheet("color: blue") label4 = QLabel(self.label) label4.setText("bias") label4.move(397, 215) label4.setFont(font2) label4.setStyleSheet("color: blue") label5 = QLabel(self.label) label5.setText("I") label5.move(77, 77) label5.setFont(font1) label5.setStyleSheet("color: blue") label6 = QLabel(self.label) label6.setText("bias") label6.move(82, 85) label6.setFont(font2) label6.setStyleSheet("color: blue") label7 = QLabel(self.label) label7.setText("2I") label7.move(340, 77) label7.setFont(font1) label7.setStyleSheet("color: blue") label8 = QLabel(self.label) label8.setText("bias") label8.move(355, 85) label8.setFont(font2) label8.setStyleSheet("color: blue") label9 = QLabel(self.label) label9.setText("I") label9.move(552, 77) label9.setFont(font1) label9.setStyleSheet("color: blue") label10 = QLabel(self.label) label10.setText("bias") label10.move(557, 85) label10.setFont(font2) label10.setStyleSheet("color: blue") # set icon for the application def setIcon(self): appIcon = QIcon("icon.png") self.setWindowIcon(appIcon) # to center the application window at the beginning def center(self): qRect = self.frameGeometry() centerPoint = QtGui.QGuiApplication.primaryScreen().availableGeometry( ).center() qRect.moveCenter(centerPoint) self.move(qRect.topLeft()) def mousePressEvent(self, event: QMouseEvent): self.colorDefaultLabels() self.redClickedTransistor(event.x(), event.y()) # red the transistor if the mouse position within its range def redClickedTransistor(self, x, y): x1_a1 = 230 y1_a1 = 280 x2_a1 = 290 y2_a1 = 230 x1_b1 = 365 y1_b1 = 280 x2_b1 = 425 y2_b1 = 230 x1_a2 = 100 y1_a2 = 400 x2_a2 = 170 y2_a2 = 350 x1_b2 = 490 y1_b2 = 400 x2_b2 = 555 y2_b2 = 350 x1_a3 = 100 y1_a3 = 320 x2_a3 = 170 y2_a3 = 265 x1_b3 = 490 y1_b3 = 320 x2_b3 = 555 y2_b3 = 265 x1_a4 = 100 y1_a4 = 210 x2_a4 = 170 y2_a4 = 160 x1_b4 = 490 y1_b4 = 210 x2_b4 = 555 y2_b4 = 160 x1_a5 = 100 y1_a5 = 145 x2_a5 = 170 y2_a5 = 95 x1_b5 = 490 y1_b5 = 145 x2_b5 = 555 y2_b5 = 95 x1_6 = 280 y1_6 = 180 x2_6 = 345 y2_6 = 140 if self.withinRange(x, y, x1_a1, y1_a1, x2_a1, y2_a1) or self.withinRange( x, y, x1_b1, y1_b1, x2_b1, y2_b1): self.trans1a.setStyleSheet("color: red") self.trans1b.setStyleSheet("color: red") elif self.withinRange(x, y, x1_a2, y1_a2, x2_a2, y2_a2) or self.withinRange( x, y, x1_b2, y1_b2, x2_b2, y2_b2): self.trans2a.setStyleSheet("color: red") self.trans2b.setStyleSheet("color: red") elif self.withinRange(x, y, x1_a3, y1_a3, x2_a3, y2_a3) or self.withinRange( x, y, x1_b3, y1_b3, x2_b3, y2_b3): self.trans3a.setStyleSheet("color: red") self.trans3b.setStyleSheet("color: red") elif self.withinRange(x, y, x1_a4, y1_a4, x2_a4, y2_a4) or self.withinRange( x, y, x1_b4, y1_b4, x2_b4, y2_b4): self.trans4a.setStyleSheet("color: red") self.trans4b.setStyleSheet("color: red") elif self.withinRange(x, y, x1_a5, y1_a5, x2_a5, y2_a5) or self.withinRange( x, y, x1_b5, y1_b5, x2_b5, y2_b5): self.trans5a.setStyleSheet("color: red") self.trans5b.setStyleSheet("color: red") elif self.withinRange(x, y, x1_6, y1_6, x2_6, y2_6): self.trans6.setStyleSheet("color: red") def withinRange(self, x, y, x1, y1, x2, y2): if x >= x1 and x <= x2 and y <= y1 and y >= y2: return True else: return False
class MainWindow(QLabel): """Defines the view for the remote control.""" command_requested = Signal(str) def __init__(self): super(MainWindow, self).__init__() # Construct a QPixmap from the TiVo remote control image. self.remote_control_pixmap = QPixmap(":/assets/tivo_remote.jpg") # Scale the window to the width and height of the TiVo remote control # image and disable resizing. We disable resizing because: # # 1) there's really no point to resizing it # 2) none of the images I have are going to look good scaled up # 3) it would only serve to complicate the clickable zone logic for no # good reason (see below). self.setFixedSize(self.remote_control_pixmap.width(), self.remote_control_pixmap.height()) # Render the pixmap to the window. self.setPixmap(self.remote_control_pixmap) # Allow a context menu to be implemented. self.setContextMenuPolicy(Qt.CustomContextMenu) # Notify us when the user has right clicked on the window. self.customContextMenuRequested.connect(self.on_context_menu) # Define informational QActions to be displayed to the user on the # context menu. self.current_channel = QAction(self) self.current_channel.setEnabled(False) self.select_tivo = QAction("Connect to a different TiVo...", self) self.change_channel = QAction("Change channel...", self) self.input_text = QAction("Input text...", self) # We care about ALL movements of the user, regardless of whether or not # they're pressing buttons. self.setMouseTracking(True) # Button widgets are not used to handle input from the user, instead an # image of a TiVo remote control is displayed and the user merely has # to click on the button they wish to press as they would press it on a # real remote control. Therefore, the simplest solution is to intercept # cursor movements and check to see whether the coordinates fall within # the boundaries of a button. # # This data is also used for associating the button with a key binding. # # The data for each button is a dictionary with values of the # following: # # cmd (str): The protocol command assigned to this button. # key (int): The physical key assigned to this button. # # min_x (int): The minimum X position that the button corresponds to on # the remote control image. # # max_x (int): The maximum X position that the button corresponds to on # the remote control image. # # min_y (int): The minimum Y position that the button corresponds to on # the remote control image. # # max_y (int): The maximum Y position that the button corresponds to on # the remote control image. self.buttons = ({ "cmd": "IRCODE TIVO", "key": Qt.Key_T, "min_x": 193, "max_x": 234, "min_y": 51, "max_y": 80 }, { "cmd": "IRCODE LIVETV", "key": Qt.Key_L, "min_x": 258, "max_x": 273, "min_y": 66, "max_y": 95 }, { "cmd": "IRCODE TVINPUT", "key": Qt.Key_Space, "min_x": 131, "max_x": 147, "min_y": 110, "max_y": 135 }, { "cmd": "IRCODE UP", "key": Qt.Key_Up, "min_x": 207, "max_x": 220, "min_y": 109, "max_y": 129 }, { "cmd": "IRCODE INFO", "key": Qt.Key_I, "min_x": 279, "max_x": 300, "min_y": 110, "max_y": 132 }, { "cmd": "IRCODE LEFT", "key": Qt.Key_Left, "min_x": 161, "max_x": 179, "min_y": 153, "max_y": 174 }, { "cmd": "IRCODE SELECT", "key": Qt.Key_Return, "min_x": 200, "max_x": 236, "min_y": 143, "max_y": 188 }, { "cmd": "IRCODE RIGHT", "key": Qt.Key_Right, "min_x": 248, "max_x": 262, "min_y": 155, "max_y": 175 }, { "cmd": "IRCODE VOLUMEUP", "key": Qt.Key_Plus, "min_x": 134, "max_x": 150, "min_y": 207, "max_y": 223 }, { "cmd": "IRCODE DOWN", "key": Qt.Key_Down, "min_x": 202, "max_x": 225, "min_y": 200, "max_y": 223 }, { "cmd": "IRCODE CHANNELUP", "key": Qt.Key_PageUp, "min_x": 276, "max_x": 296, "min_y": 206, "max_y": 223 }, { "cmd": "IRCODE VOLUMEDOWN", "key": Qt.Key_Minus, "min_x": 140, "max_x": 161, "min_y": 260, "max_y": 276 }, { "cmd": "IRCODE GUIDE", "key": Qt.Key_G, "min_x": 192, "max_x": 231, "min_y": 241, "max_y": 269 }, { "cmd": "IRCODE CHANNELDOWN", "key": Qt.Key_PageDown, "min_x": 262, "max_x": 288, "min_y": 259, "max_y": 277 }, { "cmd": "IRCODE THUMBSDOWN", "key": Qt.Key_End, "min_x": 143, "max_x": 160, "min_y": 296, "max_y": 328 }, { "cmd": "IRCODE MUTE", "key": Qt.Key_M, "min_x": 178, "max_x": 204, "min_y": 281, "max_y": 308 }, { "cmd": "IRCODE RECORD", "key": Qt.Key_R, "min_x": 224, "max_x": 244, "min_y": 282, "max_y": 306 }, { "cmd": "IRCODE THUMBSUP", "key": Qt.Key_Home, "min_x": 266, "max_x": 285, "min_y": 296, "max_y": 326 }, { "cmd": "IRCODE PLAY", "key": Qt.Key_P, "min_x": 207, "max_x": 220, "min_y": 326, "max_y": 348 }, { "cmd": "IRCODE REVERSE", "key": Qt.Key_R, "min_x": 152, "max_x": 178, "min_y": 372, "max_y": 392 }, { "cmd": "IRCODE PAUSE", "key": Qt.Key_S, "min_x": 196, "max_x": 228, "min_y": 358, "max_y": 407 }, { "cmd": "IRCODE FORWARD", "key": Qt.Key_F, "min_x": 248, "max_x": 273, "min_y": 372, "max_y": 392 }, { "cmd": "KEYBOARD VIDEO_ON_DEMAND", "key": Qt.Key_V, "min_x": 189, "max_x": 238, "min_y": 463, "max_y": 484 }, { "cmd": "IRCODE ACTION_A", "key": Qt.Key_A, "min_x": 143, "max_x": 166, "min_y": 485, "max_y": 507 }, { "cmd": "IRCODE ACTION_B", "key": Qt.Key_B, "min_x": 185, "max_x": 205, "min_y": 498, "max_y": 522 }, { "cmd": "IRCODE ACTION_C", "key": Qt.Key_C, "min_x": 222, "max_x": 245, "min_y": 498, "max_y": 522 }, { "cmd": "IRCODE ACTION_D", "key": Qt.Key_D, "min_x": 261, "max_x": 283, "min_y": 485, "max_y": 509 }, { "cmd": "IRCODE NUM1", "key": Qt.Key_1, "min_x": 137, "max_x": 180, "min_y": 524, "max_y": 551 }, { "cmd": "IRCODE NUM2", "key": Qt.Key_2, "min_x": 192, "max_x": 231, "min_y": 534, "max_y": 560 }, { "cmd": "IRCODE NUM3", "key": Qt.Key_3, "min_x": 247, "max_x": 294, "min_y": 526, "max_y": 550 }, { "cmd": "IRCODE NUM4", "key": Qt.Key_4, "min_x": 134, "max_x": 175, "min_y": 560, "max_y": 586 }, { "cmd": "IRCODE NUM5", "key": Qt.Key_5, "min_x": 192, "max_x": 236, "min_y": 568, "max_y": 596 }, { "cmd": "IRCODE NUM6", "key": Qt.Key_6, "min_x": 253, "max_x": 295, "min_y": 559, "max_y": 589 }, { "cmd": "IRCODE NUM7", "key": Qt.Key_7, "min_x": 128, "max_x": 170, "min_y": 594, "max_y": 620 }, { "cmd": "IRCODE NUM8", "key": Qt.Key_8, "min_x": 192, "max_x": 232, "min_y": 603, "max_y": 630 }, { "cmd": "IRCODE NUM9", "key": Qt.Key_9, "min_x": 257, "max_x": 295, "min_y": 593, "max_y": 621 }, { "cmd": "IRCODE CLEAR", "key": Qt.Key_Backspace, "min_x": 127, "max_x": 167, "min_y": 628, "max_y": 656 }, { "cmd": "IRCODE NUM0", "key": Qt.Key_0, "min_x": 194, "max_x": 230, "min_y": 639, "max_y": 667 }, { "cmd": "IRCODE ENTER", "key": Qt.Key_Enter, "min_x": 257, "max_x": 301, "min_y": 628, "max_y": 656 }) # The current button that the cursor is hovering over. self.current_button = {} def mouseMoveEvent(self, event): """Called when the cursor moves over the remote control.""" # Every time a user makes a move, we have to check and see if the # cursor is hovering over a position we care about. for button in self.buttons: # Grab the X and Y positions of the cursor. We do this here so as # to not repeatedly call it over and over again in the following # code. x = event.x() y = event.y() # Is the cursor within the ranges of a button's bounding box? if (x >= button["min_x"] and x <= button["max_x"]) and \ (y >= button["min_y"] and y <= button["max_y"]): # Yes, save the current button the user is hovering over. This # will prevent us from having to iterate again if the user # clicks on the zone. self.current_button = button # Change the cursor to pointing hand to signify that this area # is indeed clickable. self.setCursor(Qt.PointingHandCursor) break # The cursor is not hovering over a button, clear the current # button and return the cursor to normal. self.current_button = {} self.unsetCursor() def mousePressEvent(self, event): """Called when the mouse is left clicked on the remote control.""" # It is very possible that the user will just click regardless of # whether or not they're hovering over a zone, so this check is # necessary. if self.current_button: # The user is pressing a button, dispatch the command string for # it. self.command_requested.emit(self.current_button["cmd"]) def keyPressEvent(self, event): """Called when the user presses a key on the keyboard.""" for button in self.buttons: if button["key"] == event.key(): self.command_requested.emit(button["cmd"]) break @Slot(QPoint) def on_context_menu(self, point): """Called when the mouse is right clicked on the remote control.""" menu = QMenu(self) menu.addAction(self.current_channel) menu.addSeparator() menu.addAction(self.select_tivo) menu.addAction(self.input_text) menu.addAction(self.change_channel) menu.exec_(self.mapToGlobal(point)) def update_channel(self, channel): """ Updates the information specifying to the user what channel their TiVo is currently tuned into. """ self.current_channel.setText(f"Current channel: {channel}")
if __name__ == '__main__': app = QApplication.instance() if app is None: app = QApplication([]) loop = quamash.QEventLoop(app) asyncio.set_event_loop(loop) splash_pix = QPixmap('./images/splash.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) splash.setEnabled(False) # splash = QSplashScreen(splash_pix) # adding progress bar progressBar = QProgressBar(splash) progressBar.setMaximum(10) progressBar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20) # splash.setMask(splash_pix.mask()) splash.show() splash.showMessage( "<h1><font color='black' size= 10>New Neuro Spec !</font></h1>", Qt.AlignTop | Qt.AlignCenter, Qt.black) for i in range(1, 11): progressBar.setValue(i) t = time() while time() < t + 0.1: app.processEvents() # Simulate something that takes time with loop:
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())