def data(self, index, role): target = self.targets[index.row()] if index.isValid() and (0 <= index.row() < len( self.targets)) and target: column = index.column() if role == Qt.DecorationRole: if column == 1: picturePath = os.path.join(GeneralUtilities.getTempDir(), target['targetPicture']) if picturePath and os.path.exists(picturePath): pixmap = QPixmap(picturePath) return QIcon( pixmap.scaled(30, 30, Qt.IgnoreAspectRatio, Qt.FastTransformation)) else: pixmap = QPixmap(':/creepy/user') pixmap.scaled(20, 20, Qt.IgnoreAspectRatio) return QIcon(pixmap) if role == Qt.DisplayRole: if column == 0: return QVariant(target['pluginName']) elif column == 1: return QVariant() elif column == 2: return QVariant(target['targetUsername']) elif column == 3: return QVariant(target['targetFullname']) elif column == 4: return QVariant(target['targetUserid']) else: return QVariant()
def data(self, index, role): plugin = self.plugins[index.row()][0] if index.isValid(): if role == Qt.DisplayRole: return QVariant(plugin.name) if role == Qt.DecorationRole: for directory in GeneralUtilities.getPluginDirs(): picturePath = os.path.join(directory, plugin.plugin_object.name, 'logo.png') if picturePath and os.path.exists(picturePath): pixmap = QPixmap(picturePath) return QIcon( pixmap.scaled(30, 30, Qt.IgnoreAspectRatio, Qt.FastTransformation)) pixmap = QPixmap( os.path.join(GeneralUtilities.getIncludeDir(), 'generic_plugin.png')) pixmap.scaled(30, 30, Qt.IgnoreAspectRatio) return QIcon(pixmap) if role == Qt.CheckStateRole: if plugin: return Qt.Checked if plugin.name in self.checkedPlugins else Qt.Unchecked else: return QVariant()
class ImageBox(QWidget): def __init__(self): super(ImageBox, self).__init__() self.img = None self.scaled_img = None self.point = QPoint(0, 0) self.start_pos = None self.end_pos = None self.left_click = False self.scale = 1 self.SR_flag = False def init_ui(self): self.setWindowTitle("ImageBox") def set_image(self, img_path): """ open image file :param img_path: image file path :return: """ self.img = QPixmap(img_path) if self.SR_flag: self.scaled_img = self.img.scaled(self.size(), Qt.KeepAspectRatio, Qt.FastTransformation) self.SR_flag = False else: self.scaled_img = self.img.scaled(self.img.size(), Qt.KeepAspectRatio, Qt.FastTransformation) def paintEvent(self, e): if self.scaled_img: painter = QPainter() painter.begin(self) painter.scale(self.scale, self.scale) painter.drawPixmap(self.point, self.scaled_img) painter.end() def mouseMoveEvent(self, e): if self.left_click: self.end_pos = e.pos() - self.start_pos self.point = self.point + self.end_pos self.start_pos = e.pos() self.repaint() def mousePressEvent(self, e): if e.button() == Qt.LeftButton: self.left_click = True self.start_pos = e.pos() def mouseReleaseEvent(self, e): if e.button() == Qt.LeftButton: self.left_click = False
def paint(self, painter, option, index): name = index.data(Qt.DisplayRole) sz = human_readable(index.data(Qt.UserRole)) pmap = index.data(Qt.UserRole + 1) irect = option.rect.adjusted(0, 5, 0, -5) irect.setRight(irect.left() + 70) if pmap is None: pmap = QPixmap( current_container().get_file_path_for_processing(name)) scaled, nwidth, nheight = fit_image(pmap.width(), pmap.height(), irect.width(), irect.height()) if scaled: pmap = pmap.scaled(nwidth, nheight, transformMode=Qt.SmoothTransformation) index.model().setData(index, pmap, Qt.UserRole + 1) x, y = (irect.width() - pmap.width()) // 2, (irect.height() - pmap.height()) // 2 r = irect.adjusted(x, y, -x, -y) QStyledItemDelegate.paint(self, painter, option, empty_index) painter.drawPixmap(r, pmap) trect = irect.adjusted(irect.width() + 10, 0, 0, 0) trect.setRight(option.rect.right()) painter.save() if option.state & QStyle.State_Selected: painter.setPen( QPen(option.palette.color(option.palette.HighlightedText))) painter.drawText(trect, Qt.AlignVCenter | Qt.AlignLeft, name + '\n' + sz) painter.restore()
class CoverView(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.current_pixmap_size = QSize(0, 0) self.pixmap = QPixmap() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def set_pixmap(self, data): self.pixmap.loadFromData(data) self.current_pixmap_size = self.pixmap.size() self.update() def paintEvent(self, event): if self.pixmap.isNull(): return canvas_size = self.rect() width = self.current_pixmap_size.width() extrax = canvas_size.width() - width if extrax < 0: extrax = 0 x = int(extrax / 2.0) height = self.current_pixmap_size.height() extray = canvas_size.height() - height if extray < 0: extray = 0 y = int(extray / 2.0) target = QRect(x, y, min(canvas_size.width(), width), min(canvas_size.height(), height)) p = QPainter(self) p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) p.drawPixmap(target, self.pixmap.scaled(target.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) p.end() def sizeHint(self): return QSize(300, 400)
def simgv_load_image_to_viewer(self, index): """ Load an image to viewer. If the show feature points is checked, then load feature points as well. This option can be done only if the user has run a feature point method first. :param index: index of image to load. :return: Nothing """ if self.draw_kp: img_rgb = self.image_list[index].img_get_img_rgb_with_feature_points() feature_point_number = len(self.image_list[index].feature_points.keypoints) self.ui_simple_img_viewer.label_feature_points_number.setText(str(feature_point_number)) else: img_rgb = self.image_list[index].img_get_img_rgb() self.ui_simple_img_viewer.label_feature_points_number.clear() bytes_per_line = 3 * self.image_list[index].info.width q_img = QImage(img_rgb, self.image_list[index].info.width, self.image_list[index].info.height, bytes_per_line, QImage.Format_RGB888) width = self.ui_simple_img_viewer.image_view.width() height = self.ui_simple_img_viewer.image_view.height() if q_img.width() < width or q_img.height() < height: width = q_img.width() height = q_img.height() size = QSize(width, height) pixmap = QPixmap() pixmap = pixmap.fromImage(q_img) pixmap = pixmap.scaled(size, self.Q_ASPECT_RATIO) self.ui_simple_img_viewer.image_view.setPixmap(pixmap) self.ui_simple_img_viewer.image_view.show() self.ui_simple_img_viewer.button_previous.setEnabled(self.UP) self.ui_simple_img_viewer.button_next.setEnabled(self.UP) if index == 0: self.ui_simple_img_viewer.button_previous.setEnabled(self.DOWN) if index == len(self.image_list) - 1: self.ui_simple_img_viewer.button_next.setEnabled(self.DOWN)
def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize): p = QPixmap() p.loadFromData(data, encoding, Qt.AutoColor) w, h = p.width(), p.height() p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0)) if p.width() != xsize or p.height() != ysize: p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) QGraphicsPixmapItem.__init__(self, p) self.height, self.width = ysize, xsize self.setTransformationMode(Qt.SmoothTransformation) self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize): p = QPixmap() p.loadFromData(data, encoding, Qt.ImageConversionFlag.AutoColor) w, h = p.width(), p.height() p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0)) if p.width() != xsize or p.height() != ysize: p = p.scaled(xsize, ysize, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) QGraphicsPixmapItem.__init__(self, p) self.height, self.width = ysize, xsize self.setTransformationMode(Qt.TransformationMode.SmoothTransformation) self.setShapeMode(QGraphicsPixmapItem.ShapeMode.BoundingRectShape)
def set_space_icon(self, label, free_space): self.log.debug("set_space_icon: %a", free_space) if free_space <= self.critical_space: icon = QPixmap(const.IMG_ERR) elif free_space <= self.low_space: icon = QPixmap(const.IMG_WARN) else: icon = QPixmap(const.IMG_OK) label.setText("") # use a square of the height label.setPixmap( icon.scaled(label.height(), label.height(), Qt.KeepAspectRatio))
def update_img_view(self): if self.is_img_Open: #print(self.ui.img_view.size()) width = self.ui.img_view.width() height = self.ui.img_view.height() if self.img.width < width or self.img.height < height: width = self.q_img.width() height = self.q_img.height() size = QSize(width, height) pixmap = QPixmap() pixmap = pixmap.fromImage(self.q_img) pixmap = pixmap.scaled(size, self.Q_ASPECT_RATIO) self.ui.img_view.setPixmap(pixmap) self.ui.img_view.show()
def cached_emblem(self, cache, name, raw_icon=None): ans = cache.get(name, False) if ans is not False: return ans sz = self.emblem_size ans = None if raw_icon is not None: ans = raw_icon.pixmap(sz, sz) elif name == ':ondevice': ans = QPixmap(I('ok.png')).scaled(sz, sz, transformMode=Qt.SmoothTransformation) elif name: pmap = QPixmap(os.path.join(config_dir, 'cc_icons', name)) if not pmap.isNull(): ans = pmap.scaled(sz, sz) cache[name] = ans return ans
def set_color(self): r, g, b = gprefs['cover_grid_color'] pal = QPalette() col = QColor(r, g, b) pal.setColor(pal.Base, col) tex = gprefs['cover_grid_texture'] if tex: from calibre.gui2.preferences.texture_chooser import texture_path path = texture_path(tex) if path: pm = QPixmap(path) if not pm.isNull(): val = pm.scaled(1, 1).toImage().pixel(0, 0) r, g, b = qRed(val), qGreen(val), qBlue(val) pal.setBrush(pal.Base, QBrush(pm)) dark = (r + g + b)/3.0 < 128 pal.setColor(pal.Text, QColor(Qt.white if dark else Qt.black)) self.setPalette(pal) self.delegate.highlight_color = pal.color(pal.Text)
def set_color(self): r, g, b = gprefs['cover_grid_color'] pal = QPalette() col = QColor(r, g, b) pal.setColor(pal.Base, col) tex = gprefs['cover_grid_texture'] if tex: from calibre.gui2.preferences.texture_chooser import texture_path path = texture_path(tex) if path: pm = QPixmap(path) if not pm.isNull(): val = pm.scaled(1, 1).toImage().pixel(0, 0) r, g, b = qRed(val), qGreen(val), qBlue(val) pal.setBrush(pal.Base, QBrush(pm)) dark = (r + g + b) / 3.0 < 128 pal.setColor(pal.Text, QColor(Qt.white if dark else Qt.black)) self.setPalette(pal) self.delegate.highlight_color = pal.color(pal.Text)
class CoverView(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.current_pixmap_size = QSize(0, 0) self.pixmap = QPixmap() self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) def set_pixmap(self, data): self.pixmap.loadFromData(data) self.current_pixmap_size = self.pixmap.size() self.update() def paintEvent(self, event): if self.pixmap.isNull(): return canvas_size = self.rect() width = self.current_pixmap_size.width() extrax = canvas_size.width() - width if extrax < 0: extrax = 0 x = int(extrax / 2.) height = self.current_pixmap_size.height() extray = canvas_size.height() - height if extray < 0: extray = 0 y = int(extray / 2.) target = QRect(x, y, min(canvas_size.width(), width), min(canvas_size.height(), height)) p = QPainter(self) p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform) p.drawPixmap( target, self.pixmap.scaled(target.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)) p.end() def sizeHint(self): return QSize(300, 400)
def show_erd(self): if self.question != '': image_dialog = QDialog() image_dialog.setModal(False) if self.erd is None: image_label = QLabel("No Diagram set for Question") else: image_label = QLabel(self.erd) image = QPixmap(os.path.join(self.dir_path, "images", self.erd)) image_label.setPixmap( image.scaled(1024, 768, Qt.KeepAspectRatio)) layout = QBoxLayout(QBoxLayout.LeftToRight) layout.addWidget(image_label) image_label.setScaledContents(True) image_label.setMinimumHeight(100) image_label.setMinimumWidth(100) image_dialog.setLayout(layout) image_dialog.setModal(False) image_dialog.exec()
def set_color(self): r, g, b = gprefs['cover_grid_color'] tex = gprefs['cover_grid_texture'] pal = self.palette() pal.setColor(pal.Base, QColor(r, g, b)) self.setPalette(pal) ss = '' if tex: from calibre.gui2.preferences.texture_chooser import texture_path path = texture_path(tex) if path: path = os.path.abspath(path).replace(os.sep, '/') ss += 'background-image: url({});'.format(path) ss += 'background-attachment: fixed;' pm = QPixmap(path) if not pm.isNull(): val = pm.scaled(1, 1).toImage().pixel(0, 0) r, g, b = qRed(val), qGreen(val), qBlue(val) dark = max(r, g, b) < 115 ss += 'color: {};'.format('white' if dark else 'black') self.delegate.highlight_color = QColor(Qt.white if dark else Qt.black) self.setStyleSheet('QListView {{ {} }}'.format(ss))
def paint(self, painter, option, index): name = index.data(Qt.DisplayRole) sz = human_readable(index.data(Qt.UserRole)) pmap = index.data(Qt.UserRole+1) irect = option.rect.adjusted(0, 5, 0, -5) irect.setRight(irect.left() + 70) if pmap is None: pmap = QPixmap(current_container().get_file_path_for_processing(name)) scaled, nwidth, nheight = fit_image(pmap.width(), pmap.height(), irect.width(), irect.height()) if scaled: pmap = pmap.scaled(nwidth, nheight, transformMode=Qt.SmoothTransformation) index.model().setData(index, pmap, Qt.UserRole+1) x, y = (irect.width() - pmap.width())//2, (irect.height() - pmap.height())//2 r = irect.adjusted(x, y, -x, -y) QStyledItemDelegate.paint(self, painter, option, QModelIndex()) painter.drawPixmap(r, pmap) trect = irect.adjusted(irect.width() + 10, 0, 0, 0) trect.setRight(option.rect.right()) painter.save() if option.state & QStyle.State_Selected: painter.setPen(QPen(option.palette.color(option.palette.HighlightedText))) painter.drawText(trect, Qt.AlignVCenter | Qt.AlignLeft, name + '\n' + sz) painter.restore()
def __init__(self): QMainWindow.__init__(self) self.setupUi(self) # self.lineEdit.textChanged['QString'].connect(self.mensaje) simplex = QAction("SIMPLEX", self) simplex.setShortcut("Ctrl+S") self.menuM_todos.addAction(simplex) simplex.triggered.connect(self.ui_simplex) transporte = QAction("TRANSPORTE", self) transporte.setShortcut("Ctrl+T") self.menuM_todos.addAction(transporte) transporte.triggered.connect(self.ui_transporte) # self.resize(640,480) self.setFixedSize(640, 360) background = QPixmap(":/back.jpg") background = background.scaled(self.size()) pal = self.palette() pal.setBrush(QPalette.Background, QBrush(background)) self.setPalette(pal) self.setStyleSheet(" QMenuBar{ background-color: #e1e1e1} ") self.btnSimplex.clicked.connect(simplex.trigger) self.btnTransporte.clicked.connect(transporte.trigger) dev = QAction("Desarrolador", self) dev.setShortcut("Ctrl+D") self.menuAcerca_de.addAction(dev) dev.triggered.connect(self.about_dev)
def update_host(self, host_item=None): """ Update HostQWidget data and QLabels :param host_item: the Host item :type host_item: alignak_app.items.host.Host """ if self.host_item and not host_item: self.set_data(self.host_item) if host_item: self.set_data(host_item) if self.host_item or host_item: # Update host services self.refresh_counter += 1 if self.refresh_counter > 10: thread_manager.add_high_priority_thread('service', self.host_item.item_id) self.refresh_counter = 0 # Update host icon_name = get_overall_state_icon( self.service_items, self.host_item.data['_overall_state_id'] ) icon_pixmap = QPixmap(settings.get_image(icon_name)) self.labels['host_icon'].setPixmap(QPixmap(icon_pixmap)) self.labels['host_icon'].setToolTip( self.host_item.get_overall_tooltip(self.service_items) ) self.labels['host_name'].setText('%s' % self.host_item.get_display_name()) monitored = self.host_item.data[ 'passive_checks_enabled'] + self.host_item.data['active_checks_enabled'] icon_name = get_icon_name( 'host', self.host_item.data['ls_state'], self.host_item.data['ls_acknowledged'], self.host_item.data['ls_downtimed'], monitored ) pixmap_icon = QPixmap(settings.get_image(icon_name)) final_icon = pixmap_icon.scaled(32, 32, Qt.KeepAspectRatio) self.labels['state_icon'].setPixmap(final_icon) self.labels['state_icon'].setToolTip(self.host_item.get_tooltip()) since_last_check = get_diff_since_last_timestamp( self.host_item.data['ls_last_check'] ) last_check_tooltip = get_date_fromtimestamp(self.host_item.data['ls_last_check']) self.labels['ls_last_check'].setText(since_last_check) self.labels['ls_last_check'].setToolTip(last_check_tooltip) self.labels['ls_output'].setText(self.host_item.data['ls_output']) self.labels['realm'].setText( data_manager.get_realm_name(self.host_item.data['_realm']) ) self.labels['address'].setText(self.host_item.data['address']) self.labels['business_impact'].setText(str(self.host_item.data['business_impact'])) self.labels['notes'].setText(self.host_item.data['notes']) self.actions_widget.item = self.host_item self.actions_widget.update_widget() self.activecheck_btn.update_btn_state(self.host_item.data['active_checks_enabled']) self.passivecheck_btn.update_btn_state(self.host_item.data['passive_checks_enabled']) self.customs_btn.setEnabled(bool(self.host_item.data['customs'])) # Update host history self.host_history = data_manager.get_item('history', self.host_item.item_id) if self.host_history: self.history_btn.setEnabled(True) self.history_btn.setToolTip(_('History is available')) else: self.history_btn.setToolTip(_('History is not available, please wait...')) self.history_btn.setEnabled(False) if app_backend.connected: thread_manager.add_high_priority_thread( 'history', {'hostname': self.host_item.name, 'host_id': self.host_item.item_id} ) else: thread_manager.stop_threads()
class ImageBox(QWidget): def __init__(self): super(ImageBox, self).__init__() self.img = None self.img_array = None self.img_array_HLS = None self.width = None self.height = None self.scaled_img = None self.point = QPoint(0, 0) self.start_pos = None self.end_pos = None self.left_click = False self.scale = 1 def init_ui(self): self.setWindowTitle("ImageBox") def set_img_array(self, ndarray): self.img_array = ndarray def set_pixmap(self, ndarray): self.img_array = cv2.cvtColor(ndarray, cv2.COLOR_BGR2BGRA) qimage = QtGui.QImage(self.img_array.data, ndarray.shape[1], ndarray.shape[0], QtGui.QImage.Format_RGB32) self.width = ndarray.shape[1] # 获取图像大小 self.height = ndarray.shape[0] self.scaled_img = QtGui.QPixmap.fromImage(qimage).scaled( self.width, self.height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self.repaint() def set_image(self, img_path): """ open image file :param img_path: image file path :return: """ self.img = QPixmap(img_path) self.img_array = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1) fImg = self.img_array.astype(np.float32) fImg = fImg / 255.0 # 颜色空间转换 BGR转为HLS self.img_array_HLS = cv2.cvtColor(fImg, cv2.COLOR_BGR2HLS) self.width = self.img_array.shape[1] # 获取图像大小 self.height = self.img_array.shape[0] self.scaled_img = self.img.scaled(self.width, self.height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) def paintEvent(self, e): """ receive paint events :param e: QPaintEvent :return: """ if self.scaled_img: painter = QPainter() painter.begin(self) painter.scale(self.scale, self.scale) painter.drawPixmap(self.point, self.scaled_img) painter.end() def mouseMoveEvent(self, e): """ mouse move events for the widget :param e: QMouseEvent :return: """ if self.left_click: self.end_pos = e.pos() - self.start_pos self.point = self.point + self.end_pos self.start_pos = e.pos() self.repaint() def wheelEvent(self, event): mods = event.modifiers() # Ctrl键 if Qt.ControlModifier == int(mods): angle_delta_y = event.angleDelta().y() # 滚轮滚动 y 的值为120/-120 x为0 # print("y: " + str(event.angleDelta().y())) # print("x: " + str(event.angleDelta().x())) if angle_delta_y > 0: if self.scale < 2: self.scale += 0.01 self.adjustSize() self.update() else: if self.scale > 0.1: self.scale -= 0.01 self.adjustSize() self.update() def mousePressEvent(self, e): """ mouse press events for the widget :param e: QMouseEvent :return: """ if e.button() == Qt.LeftButton: self.left_click = True self.start_pos = e.pos() def mouseReleaseEvent(self, e): """ mouse release events for the widget :param e: QMouseEvent :return: """ if e.button() == Qt.LeftButton: self.left_click = False
def _fetch_marvin_cover(border_width=0): ''' Retrieve LargeCoverJpg from cache ''' #self._log_location('border_width: {0}'.format(border_width)) con = sqlite3.connect(self.marvin_db_path) with con: con.row_factory = sqlite3.Row # Fetch Hash from mainDb cover_cur = con.cursor() cover_cur.execute('''SELECT Hash FROM Books WHERE ID = '{0}' '''.format(self.book_id)) row = cover_cur.fetchone() book_hash = row[b'Hash'] large_covers_subpath = self.connected_device._cover_subpath( size="large") cover_path = '/'.join([large_covers_subpath, '%s.jpg' % book_hash]) stats = self.parent.ios.exists(cover_path) if stats: self._log("fetching large cover from cache") #self._log("cover size: {:,} bytes".format(int(stats['st_size']))) cover_bytes = self.parent.ios.read(cover_path, mode='rb') m_image = QImage() m_image.loadFromData(cover_bytes) if border_width: # Construct a QPixmap with oversized yellow background m_image = m_image.scaledToHeight( self.COVER_ICON_SIZE - border_width * 2, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width() + border_width * 2, m_image.height() + border_width * 2)) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.fillRect(self.m_pixmap.rect(), self.MISMATCH_COLOR) m_painter.drawImage(border_width, border_width, m_image) else: m_image = m_image.scaledToHeight(self.COVER_ICON_SIZE, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width(), m_image.height())) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.drawImage(0, 0, m_image) self.marvin_cover.setPixmap(self.m_pixmap) else: # No cover available, use generic self._log("No cached cover, using generic") pixmap = QPixmap() pixmap.load(I('book.png')) pixmap = pixmap.scaled(self.COVER_ICON_SIZE, self.COVER_ICON_SIZE, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) self.marvin_cover.setPixmap(pixmap)
class MyMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self.setupUi(self) self.setMouseTracking(True) self.imglist = [] self.ImgFolder = '' self.CurImg = '' #新建QPixmap作为画板,尺寸为__size self.__board = QPixmap() self.__board.fill(Qt.white) #用白色填充画板 self.__IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 self.__painter = QPainter() # 新建绘图工具 self.__thickness = 10 # 默认画笔粗细为10px self.__penColor = QColor("black") # 设置默认画笔颜色为黑色 self.__colorList = QColor.colorNames() # 获取颜色列表 # 按键信号与回调函数连接 self.OpenDir.clicked.connect(self.OpenDirBntClicked) self.NextImg.clicked.connect(self.NextImBntClicked) self.LastImg.clicked.connect(self.PreImBntClicked) self.SaveImg.clicked.connect(self.on_btn_Save_Clicked) self.PenThicknessSpinBox.valueChanged.connect(self.on_PenThicknessChange) # self.NextImg.clicked.connect(self.NextImBntClicked) #########选择图片文件夹######### def OpenDirBntClicked(self): self.ImgFolder = QtWidgets.QFileDialog.getExistingDirectory(None, "select folder", DefaultImFolder) # 这个语句有些邪门 if self.ImgFolder != '': ImNameSet = os.listdir(self.ImgFolder) self.imglist = glob.glob(self.ImgFolder + '/*.jpg') print(self.imglist) print(ImNameSet) ImNameSet.sort() # ImPath = os.path.join(ImFolder, ImNameSet[0]) ImPath = os.path.join(self.ImgFolder, ImNameSet[1]) # pix = QtGui.QPixmap(ImPath) # self.ImgShowLabel.setPixmap(pix) # 画板 # self.__board = QtGui.QPixmap(r'C:\Users\49942\Pictures\Saved Pictures\t2.jpg') self.__board = QtGui.QPixmap(self.imglist[0]) self.__board = self.__board.scaled(500,500) # self.__IsEmpty = True # 默认为空画板 # self.EraserMode = False # 默认为禁用橡皮擦模式 # # self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 # self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 # # self.__painter = QPainter() # 新建绘图工具 # # self.__thickness = 5 # 默认画笔粗细为10px # self.__penColor = QColor("black") # 设置默认画笔颜色为黑色 # self.__colorList = QColor.colorNames() # 获取颜色列表 # 界面标题 self.ImNameSet = ImNameSet self.CurImId = 0 _, SelectFolderName = os.path.split(self.ImgFolder) CopyImFolderName = 'From{}CopyIm_{}-{}-{}-{}'.format(SelectFolderName, Month, Day, Hour, Minute) self.CopyImFolder = os.path.join(CurFolder, CopyImFolderName) _translate = QtCore.QCoreApplication.translate CurWinTitle = "检测工具 " + \ " " + \ SelectFolderName + '\\' + ImNameSet[0] self.setWindowTitle(_translate("MainWindow", '审查工具 '+self.imglist[0])) else: print('请重新选择文件夹') #########显示下一张图片 ######### def NextImBntClicked(self): ImFolder = self.ImgFolder # ImNameSet = self.ImNameSet CurImId = self.CurImId ImNum = len(self.imglist) if CurImId < ImNum - 1: # 不可循环看图 ImPath = os.path.join(ImFolder, self.imglist[CurImId + 1]) self.__board = QtGui.QPixmap(self.imglist[CurImId + 1]) self.__board = self.__board.scaled(500, 500) self.update() # self.ImgShowLabel.setPixmap(pix) self.CurImId = CurImId + 1 _, SelectFolderName = os.path.split(ImFolder) _translate = QtCore.QCoreApplication.translate CurWinTitle = "审查图片 " + \ " " + \ SelectFolderName + '\\' self.setWindowTitle(_translate("MainWindow", self.imglist[CurImId + 1])) #########显示前一张图片 ######### def PreImBntClicked(self): ImFolder = self.ImgFolder ImNameSet = self.ImNameSet CurImId = self.CurImId ImNum = len(self.imglist) if CurImId > 0: # 第一张图片没有前一张 ImPath = os.path.join(ImFolder, ImNameSet[CurImId - 1]) self.__board = QtGui.QPixmap(self.imglist[CurImId - 1]) self.__board = self.__board.scaled(500,500) self.update() # self.ImgShowLabel.setPixmap(pix) self.CurImId = CurImId - 1 _, SelectFolderName = os.path.split(ImFolder) _translate = QtCore.QCoreApplication.translate CurWinTitle = "看图工具1.0 " + \ " " + \ SelectFolderName + '\\' self.setWindowTitle(_translate("MainWindow", self.imglist[CurImId - 1])) if self.CurImId < 0: self.CurImId = 0 def Clear(self): # 清空画板 self.__board.fill(Qt.white) self.update() self.__IsEmpty = True def ChangePenColor(self, color="black"): # 改变画笔颜色 self.__penColor = QColor(color) def ChangePenThickness(self, thickness=10): # 改变画笔粗细 self.__thickness = thickness def IsEmpty(self): # 返回画板是否为空 return self.__IsEmpty def GetContentAsQImage(self): # 获取画板内容(返回QImage) image = self.__board.toImage() return image def paintEvent(self, paintEvent): # 绘图事件 # 绘图时必须使用QPainter的实例,此处为__painter # 绘图在begin()函数与end()函数间进行 # begin(param)的参数要指定绘图设备,即把图画在哪里 # drawPixmap用于绘制QPixmap类型的对象 self.__painter.begin(self) # 0,0为绘图的左上角起点的坐标,__board即要绘制的图 self.__painter.drawPixmap(0, 0, self.__board) self.__painter.end() def mousePressEvent(self, mouseEvent): # 鼠标按下时,获取鼠标的当前位置保存为上一次位置 self.__currentPos = mouseEvent.pos() self.__lastPos = self.__currentPos def mouseMoveEvent(self, mouseEvent): # 鼠标移动时,更新当前位置,并在上一个位置和当前位置间画线 self.__currentPos = mouseEvent.pos() if mouseEvent.buttons() == QtCore.Qt.LeftButton: self.__painter.begin(self.__board) if self.EraserMode == False: # 非橡皮擦模式 self.__painter.setPen(QPen(self.__penColor, self.__thickness)) # 设置画笔颜色,粗细 else: # 橡皮擦模式下画笔为纯白色,粗细为10 self.__painter.setPen(QPen(Qt.white, 10)) # 画线 self.__painter.drawLine(self.__lastPos, self.__currentPos) self.__painter.end() self.__lastPos = self.__currentPos self.update() # 更新显示 self.mouseEventpos = mouseEvent.pos() # pos = self.mapToGlobal(mouseEvent.pos()) #相對位置轉絕對 # print(pos) pos = QCursor.pos() hwnd = win32gui.WindowFromPoint((pos.x(), pos.y())) print('x,y', pos.x(), pos.y()) print(*win32gui.GetWindowRect(hwnd)) # self.frameWidget.setRect(*win32gui.GetWindowRect(hwnd)) # 截图 screen = QApplication.primaryScreen() # 获取主显示屏对象(QScreen对象) if screen is not None: image = screen.grabWindow(0, pos.x() - 60, pos.y() - 60, 120, 120) if not image.isNull(): self.EnlargeImg.setPixmap(image.scaled(240, 240)) # self.EnlargeImg.update() def mouseReleaseEvent(self, mouseEvent): self.__IsEmpty = False # 画板不再为空 # def leaveEvent(self, event): # # super(Label, self).leaveEvent(event) # # 得到鼠标在屏幕中的位置 # print('鼠标离开') # print(event) # pos = QCursor.pos() # print(pos) # hwnd = win32gui.WindowFromPoint((pos.x(), pos.y())) # print('x,y', pos.x(), pos.y()) # print(*win32gui.GetWindowRect(hwnd)) # # self.frameWidget.setRect(*win32gui.GetWindowRect(hwnd)) # # 截图 # screen = QApplication.primaryScreen() # 获取主显示屏对象(QScreen对象) # if screen is not None: # image = screen.grabWindow(0, pos.x() - 60, pos.y() - 60, 120, 120) # if not image.isNull(): # self.EnlargeImg.setPixmap(image.scaled(240, 240)) # # self.EnlargeImg.update() def on_PenColorChange(self): color_index = self.__comboBox_penColor.currentIndex() color_str = self.__colorList[color_index] self.__paintBoard.ChangePenColor(color_str) def on_PenThicknessChange(self): penThickness = self.__spinBox_penThickness.value() self.__paintBoard.ChangePenThickness(penThickness) def on_btn_Save_Clicked(self): # savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.png') # print(savePath) curImg = self.imglist[self.CurImId] ImgName = os.path.split(curImg)[-1] savePath = os.path.join(r'C:\Users\49942\Pictures', ImgName) print('保存') print(savePath) if savePath == "": print("Save cancel") return image = self.__board.toImage() image.save(savePath) def on_cbtn_Eraser_clicked(self): if self.__cbtn_Eraser.isChecked(): self.__paintBoard.EraserMode = True # 进入橡皮擦模式 else: self.__paintBoard.EraserMode = False # 退出橡皮擦模式 def Quit(self): self.close()
class SplashScreen(QSplashScreen): TITLE_SIZE = 20 # pt BODY_SIZE = 12 # pt FOOTER_SIZE = 9 # pt LOGO_SIZE = 96 # px WIDTH = 550 # px def __init__(self, develop=False): self.drawn_once = False self.develop = develop self.title_font = f = QFont() f.setPointSize(self.TITLE_SIZE) f.setBold(True) self.title_height = QFontMetrics(f).lineSpacing() + 2 self.body_font = f = QFont() f.setPointSize(self.BODY_SIZE) self.line_height = QFontMetrics(f).lineSpacing() self.total_height = max(self.LOGO_SIZE, self.title_height + 3 * self.line_height) self.num_font = f = QFont() f.setPixelSize(self.total_height) f.setItalic(True), f.setBold(True) f = QFontMetrics(f) self.num_ch = str(max(3, numeric_version[0])) self.footer_font = f = QFont() f.setPointSize(self.FOOTER_SIZE) f.setItalic(True) self.dpr = QApplication.instance().devicePixelRatio() self.pmap = QPixmap(I('library.png', allow_user_override=False)) self.pmap.setDevicePixelRatio(self.dpr) self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE), int(self.dpr * self.LOGO_SIZE), transformMode=Qt.SmoothTransformation) self.light_brush = QBrush(QColor('#F6F3E9')) self.dark_brush = QBrush(QColor('#39322B')) pmap = QPixmap(int(self.WIDTH * self.dpr), int(self.WIDTH * self.dpr)) pmap.setDevicePixelRatio(self.dpr) pmap.fill(Qt.transparent) QSplashScreen.__init__(self, pmap) self.setWindowTitle(__appname__) def drawContents(self, painter): self.drawn_once = True painter.save() painter.setRenderHint(painter.TextAntialiasing, True) painter.setRenderHint(painter.Antialiasing, True) pw = self.LOGO_SIZE height = max(pw, self.total_height) width = self.width() # Draw frame y = (self.height() - height) // 2 bottom = y + height painter.fillRect(0, y, width, height, self.light_brush) painter.fillRect(0, y, width, self.title_height, self.dark_brush) painter.fillRect(0, y, pw, height, self.dark_brush) dy = (height - self.LOGO_SIZE) // 2 painter.drawPixmap(0, y + dy, self.pmap) # Draw number painter.setFont(self.num_font) num_width = painter.boundingRect(0, 0, 0, 0, Qt.AlignCenter | Qt.TextSingleLine, self.num_ch).width() + 12 num_x = width - num_width painter.setPen(QPen(QColor('#d6b865'))) painter.drawText(num_x, y, num_width, height, Qt.AlignCenter | Qt.TextSingleLine, self.num_ch) # Draw title x = pw + 10 width -= num_width + 5 + x painter.setFont(self.title_font) painter.drawText(x, y, width, self.title_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, "CALIBRE") # Draw starting up message y += self.title_height + 5 painter.setPen(QPen(self.dark_brush.color())) painter.setFont(self.body_font) br = painter.drawText(x, y, width, self.line_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, _( 'Starting up, please wait...')) starting_up_bottom = br.bottom() # Draw footer m = self.message() if m and m.strip(): painter.setFont(self.footer_font) b = max(starting_up_bottom + 5, bottom - self.line_height) painter.drawText(x, b, width, self.line_height, Qt.AlignLeft | Qt.AlignTop | Qt.TextSingleLine, m) painter.restore() def show_message(self, msg): self.showMessage(msg) self.wait_for_draw() def wait_for_draw(self): # Without this the splash screen is not painted on linux and windows self.drawn_once = False st = monotonic() while not self.drawn_once and (monotonic() - st < 0.1): QApplication.instance().processEvents() def keyPressEvent(self, ev): if not self.develop: return QSplashScreen.keyPressEvent(self, ev) ev.accept() QApplication.instance().quit()
def set_obj_picture(self): pic = get_map(self.city_obj[self.city_obj_now]) qpix = QPixmap() qpix.loadFromData(pic) qpix = qpix.scaled(*IMAGE_SIZE) self.city_obj_pic.setPixmap(qpix)
class PaintBoard(QLabel): signal_right_mouse = pyqtSignal(int) signal_draw = pyqtSignal() def __init__(self, parent=None): super().__init__(parent) self.__parent = parent self.__board = QPixmap(QSize(440, 440)) self.__board.fill(Qt.transparent) self.__board_old = self.__board.copy() self.__board_old_old = self.__board.copy() self.__board_before_dots = self.__board.copy() self.__thickness = 10 # 默认画笔粗细为10px self.__penColor = QColor(0, 0, 0, 128) self.__painter = QPainter() self.__pen = QPen(self.__penColor, self.__thickness) self.__pen_seg = QPen(QColor(0, 0, 0, 128)) self.__brush = QBrush(QColor(0, 0, 0, 128)) self.__pen.setCapStyle(Qt.RoundCap) #self.__painter.setPen(self.__pen) self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 self.__points = [] # dots模式的点集 self.__mouse_pressed = False self.__can_undo = False self.__has_seg = False self.__mode = 1 self.__ERASE = 0 self.__LINE = 1 self.__RECT = 2 self.__CIRCLE = 3 self.__DOTS = 4 self.__transparent = False self.__trans_board = self.__board.copy() self.__trans_board.fill(Qt.transparent) @staticmethod def dist(p1, p2): return math.hypot(p1.x() - p2.x(), p1.y() - p2.y()) # Each time paintEvent is called it clean the space where it is going to draw. # So it does not save memory of the previous drawings, # A simple solution is to first paint a QPixmap to store what you have painted. # And then paint the widget with that QPixmap. def set_trans(self, trans): self.__transparent = trans self.update() def is_trans(self): return self.__transparent def paintEvent(self, paint_event): # 把board绘制到界面上 self.__painter.begin(self) if not self.__transparent: self.__painter.drawPixmap(0, 0, self.__board) else: self.__painter.drawPixmap(0, 0, self.__trans_board) #结果图关闭mask self.__painter.end() def mousePressEvent(self, mouse_event): if mouse_event.button() == Qt.LeftButton: self.__mouse_pressed = True self.__board_old_old = self.__board_old.copy() self.__board_old = self.__board.copy() self.__currentPos = mouse_event.pos() self.__lastPos = self.__currentPos if self.__mode == self.__DOTS: if len(self.__points) == 0: self.__board_before_dots = self.__board.copy() self.__parent.childAt(740, 0).setEnabled(False) self.__parent.childAt(840, 0).setEnabled(False) self.__parent.childAt(370, 0).setEnabled(False) self.__parent.childAt(300, 610).setEnabled(False) if len(self.__points) > 0: print( self.dist( self.__points[0], QPoint(self.__currentPos.x(), self.__currentPos.y()))) if len(self.__points) > 2 and \ self.dist(self.__points[0], QPoint(self.__currentPos.x(), self.__currentPos.y())) < 5: self.__board = self.__board_before_dots.copy() self.__painter.begin(self.__board) if self.__ERASE: self.__painter.setCompositionMode( QPainter.CompositionMode_Clear) else: self.__painter.setCompositionMode( QPainter.CompositionMode_Source) self.__painter.setPen(Qt.NoPen) self.__painter.setBrush(self.__brush) self.__painter.drawPolygon(QPolygon(self.__points)) self.signal_draw.emit() self.__painter.end() self.__points.clear() self.__parent.childAt(740, 0).setEnabled(True) self.__parent.childAt(840, 0).setEnabled(True) self.__parent.childAt(370, 0).setEnabled(True) self.__parent.childAt(300, 610).setEnabled(True) self.update() else: self.__points.append( QPoint(self.__currentPos.x(), self.__currentPos.y())) if not (self.__mode == self.__DOTS and len(self.__points) == 1): self.__can_undo = True self.__parent.childAt(70, 610).setEnabled(True) else: self.__can_undo = False self.__parent.childAt(70, 610).setEnabled(False) def mouseMoveEvent(self, mouse_event): # 把线绘制到board上 self.__currentPos = mouse_event.pos() if self.__mode != self.__LINE: if len(self.__points) > 0: self.__board = self.__board_old.copy() elif not self.__mode == self.__DOTS: if self.__mouse_pressed: self.__board = self.__board_old.copy() self.__painter.begin(self.__board) self.__painter.setPen(self.__pen) if self.__ERASE: self.__painter.setCompositionMode(QPainter.CompositionMode_Clear) else: self.__painter.setCompositionMode(QPainter.CompositionMode_Source) if self.__mode == self.__LINE: if self.__mouse_pressed: self.__painter.drawLine(self.__lastPos, self.__currentPos) self.signal_draw.emit() elif self.__mode == self.__RECT: self.__painter.setPen(Qt.NoPen) self.__painter.setBrush(self.__brush) if self.__mouse_pressed: self.__painter.drawRect( self.__lastPos.x(), self.__lastPos.y(), (self.__currentPos.x() - self.__lastPos.x()), (self.__currentPos.y() - self.__lastPos.y())) self.signal_draw.emit() elif self.__mode == self.__CIRCLE: self.__painter.setPen(Qt.NoPen) self.__painter.setBrush(self.__brush) if self.__mouse_pressed: self.__painter.drawEllipse( self.__lastPos.x(), self.__lastPos.y(), (self.__currentPos.x() - self.__lastPos.x()), (self.__currentPos.y() - self.__lastPos.y())) self.signal_draw.emit() elif self.__mode == self.__DOTS: if len(self.__points) > 0: self.__painter.setCompositionMode( QPainter.CompositionMode_Source) self.__painter.setPen(QPen(self.__pen_seg.color(), 1)) self.__painter.drawLine(self.__points[-1], self.__currentPos) self.signal_draw.emit() self.__painter.end() if self.__mode == self.__LINE: self.__lastPos = self.__currentPos self.update() # 触发paintEvent def mouseDoubleClickEvent(self, mouse_event): if mouse_event.button() == Qt.LeftButton: if not self.__mode == self.__DOTS: if self.__has_seg: x = mouse_event.pos().x() y = mouse_event.pos().y() value = self.segment[y][x] # 注意这里x和y要反过来 self.__painter.begin(self.__board) self.paint_segment(value, x, y) self.__painter.end() self.signal_draw.emit() self.update() # 触发paintEvent def mouseReleaseEvent(self, mouse_event): if mouse_event.button() == Qt.LeftButton: self.__mouse_pressed = False if mouse_event.button() == Qt.RightButton: self.signal_right_mouse.emit(1 - self.__ERASE) return def undo(self): if self.__can_undo: if self.__mode != self.__DOTS: self.__board = self.__board_old.copy() else: if len(self.__points) == 0: self.__board = self.__board_before_dots.copy() else: self.__points.pop() self.__board = self.__board_old_old.copy() self.__board_old = self.__board_old_old.copy() self.signal_draw.emit() self.update() self.__can_undo = False self.__parent.childAt(70, 610).setEnabled(False) def update_segment(self, seg): self.segment = seg self.__parent.childAt(1040, 0).setEnabled(False) self.__has_seg = True def set_board(self, x, y): self.__board = self.__board.scaled(x, y) def update_board(self, board): self.__board = board self.update() def paint_segment(self, value, x, y): has_painted = np.zeros(self.segment.shape, dtype=np.uint8) point_stack = [(x, y)] while len(point_stack) > 0: point = point_stack.pop() x = point[0] y = point[1] self.__painter.setPen(self.__pen_seg) if self.__ERASE: self.__painter.setCompositionMode( QPainter.CompositionMode_Clear) else: self.__painter.setCompositionMode( QPainter.CompositionMode_Source) self.__painter.drawPoint(x, y) has_painted[y][x] = 1 if x + 1 < self.segment.shape[1] and has_painted[y][ x + 1] == 0 and value == self.segment[y][x + 1]: point_stack.append((x + 1, y)) if x - 1 >= 0 and has_painted[y][ x - 1] == 0 and value == self.segment[y][x - 1]: point_stack.append((x - 1, y)) if y + 1 < self.segment.shape[0] and has_painted[ y + 1][x] == 0 and value == self.segment[y + 1][x]: point_stack.append((x, y + 1)) if y - 1 >= 0 and has_painted[ y - 1][x] == 0 and value == self.segment[y - 1][x]: point_stack.append((x, y - 1)) def Thanos(self, label): if len(label) == 0: return False image = self.__board.copy() image.fill(Qt.transparent) pixels = image.toImage() s = pixels.bits().asstring(pixels.width() * pixels.height() * 4) arr = np.fromstring(s, dtype=np.uint8).reshape( (pixels.height(), pixels.width(), 4)) np.set_printoptions(threshold=sys.maxsize) mask = arr[..., 3] for l in label: mask[self.segment == l] = 255 expand_mask(mask, 5) #Image.fromarray(np.uint8(mask)).save('mask_10.jpg') return mask def set_seg(self): self.__has_seg = False def set_pen(self, value): self.__pen.setWidth(value) def pen_black(self): self.__pen.setColor(QColor(0, 0, 0, 128)) def pen_white(self): self.__pen.setColor(QColor(255, 255, 255, 128)) def geo_black(self): self.__pen_seg.setColor(QColor(0, 0, 0, 128)) self.__brush = QBrush(QColor(0, 0, 0, 128)) def geo_white(self): self.__pen_seg.setColor(QColor(255, 255, 255, 128)) self.__brush = QBrush(QColor(255, 255, 255, 128)) def switch_mode(self): self.__ERASE = 1 - self.__ERASE def set_mode(self, mode): self.__ERASE = mode def tool_pen(self): self.__mode = self.__LINE def tool_rect(self): self.__mode = self.__RECT def tool_circle(self): self.__mode = self.__CIRCLE def tool_dots(self): self.__mode = self.__DOTS def clear_board(self): self.__board.fill(Qt.transparent) self.__board_old = self.__board.copy() self.__board_before_dots = self.__board.copy() self.__board_old_old = self.__board.copy() self.__parent.childAt(70, 610).setEnabled(False) self.signal_draw.emit() self.update() def save(self): # save_path = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.jpg') save_path = 'D:/test.png', '*.png' print(save_path) if save_path[0] == "": print("Save cancel") return image = self.__board pixels = image.toImage() s = pixels.bits().asstring(pixels.width() * pixels.height() * 4) arr = np.fromstring(s, dtype=np.uint8).reshape( (pixels.height(), pixels.width(), 4)) np.set_printoptions(threshold=sys.maxsize) mask = arr[..., 3] print(mask) # qimage2numpy(pixels) # Pixels can only be accessed through QPainter functions or by converting the QPixmap to a QImage. image.save(save_path[0]) def get_mask(self): image = self.__board pixels = image.toImage() s = pixels.bits().asstring(pixels.width() * pixels.height() * 4) arr = np.fromstring(s, dtype=np.uint8).reshape( (pixels.height(), pixels.width(), 4)) np.set_printoptions(threshold=sys.maxsize) mask = arr[..., 3] # 取alpha通道,就是不透明度 mask[mask > 0] = 255 return mask def get_board(self): return self.__board.copy() def test(self): # self.pix = QPixmap("road.jpg") self.__painter.begin(self.__board) for i in range(301): for j in range(301): self.__painter.drawPoint(i, j) self.__painter.end() self.update()
def exec_(self): dialog = QDialog(self.parent) textEdit = QTextEdit(dialog) buttonBox = QDialogButtonBox(dialog) layout = QVBoxLayout(dialog) labels = [] html = '' width = 400 height = 25 def triggeredCredit(): if textEdit.isVisible(): for i in range(2 if self.logo else 1, len(labels)): labels[i].show() textEdit.hide() else: for i in range(2 if self.logo else 1, len(labels)): labels[i].hide() textEdit.show() def triggeredClose(arg): dialog.close() dialog.setWindowTitle('About {}'.format(self.programName)) for key in self.__labelsKeys: value = self.__labels.get(key) if value: label = QLabel(dialog) label.setAlignment(Qt.AlignCenter) if key == 'website' or key == 'license': label.setText('<a href="{}">{}</a>'.format( value['url'], value['label'] if value['label'] else value['url'])) label.setTextFormat(Qt.RichText) label.setTextInteractionFlags(Qt.TextBrowserInteraction) label.setOpenExternalLinks(True) elif key == 'logo': image = QPixmap(self.logo) label.setPixmap(image.scaled(128, 128)) else: label.setText(value) labels.append(label) layout.addWidget(labels[len(labels) - 1]) for key in self.__creditsKeys: value = self.__credits.get(key) if len(value.get('contributors')) > 0: html += '<p><strong>{}</strong><br />{}</p>'.format( value.get('label'), '<br />'.join(value.get('contributors'))) if html: textEdit.setHtml('<center>{}</center>'.format(html)) layout.addWidget(textEdit) buttonBox.addButton( 'Credits', QDialogButtonBox.YesRole).clicked.connect(triggeredCredit) textEdit.close() textEdit.setReadOnly(True) buttonBox.addButton( 'Close', QDialogButtonBox.NoRole).clicked.connect(triggeredClose) layout.addWidget(buttonBox) dialog.setLayout(layout) height *= len(dialog.children()) if self.logo: height += 128 dialog.setFixedSize(width, height) return dialog.exec_()
def pixmap(self, thumbnail_height, entry): pmap = QPixmap(current_container().name_to_abspath(entry.name)) if entry.width > 0 and entry.height > 0 else QPixmap() scaled, width, height = fit_image(entry.width, entry.height, thumbnail_height, thumbnail_height) if scaled and not pmap.isNull(): pmap = pmap.scaled(width, height, transformMode=Qt.SmoothTransformation) return pmap
def _fetch_marvin_cover(border_width=0): ''' Retrieve LargeCoverJpg from cache ''' #self._log_location('border_width: {0}'.format(border_width)) con = sqlite3.connect(self.marvin_db_path) with con: con.row_factory = sqlite3.Row # Fetch Hash from mainDb cover_cur = con.cursor() cover_cur.execute('''SELECT Hash FROM Books WHERE ID = '{0}' '''.format(self.book_id)) row = cover_cur.fetchone() book_hash = row[b'Hash'] large_covers_subpath = self.connected_device._cover_subpath(size="large") cover_path = '/'.join([large_covers_subpath, '%s.jpg' % book_hash]) stats = self.parent.ios.exists(cover_path) if stats: self._log("fetching large cover from cache") #self._log("cover size: {:,} bytes".format(int(stats['st_size']))) cover_bytes = self.parent.ios.read(cover_path, mode='rb') m_image = QImage() m_image.loadFromData(cover_bytes) if border_width: # Construct a QPixmap with oversized yellow background m_image = m_image.scaledToHeight( self.COVER_ICON_SIZE - border_width * 2, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width() + border_width * 2, m_image.height() + border_width * 2)) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.fillRect(self.m_pixmap.rect(), self.MISMATCH_COLOR) m_painter.drawImage(border_width, border_width, m_image) else: m_image = m_image.scaledToHeight( self.COVER_ICON_SIZE, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width(), m_image.height())) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.drawImage(0, 0, m_image) self.marvin_cover.setPixmap(self.m_pixmap) else: # No cover available, use generic self._log("No cached cover, using generic") pixmap = QPixmap() pixmap.load(I('book.png')) pixmap = pixmap.scaled(self.COVER_ICON_SIZE, self.COVER_ICON_SIZE, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) self.marvin_cover.setPixmap(pixmap)
class SplashScreen(QSplashScreen): TITLE_SIZE = 10 # pt BODY_SIZE = 12 # pt FOOTER_SIZE = 9 # pt LOGO_SIZE = 96 # px WIDTH = 550 # px def inicio_splash(self, develop="false"): self.drawn_once = False self.develop = develop self.title_font = f = QFont() f.setPointSize(self.TITLE_SIZE) f.setBold(True) self.title_height = QFontMetrics(f).lineSpacing() self.body_font = f = QFont() f.setPointSize(self.BODY_SIZE) self.line_height = QFontMetrics(f).lineSpacing() self.total_height = max(self.LOGO_SIZE, self.title_height + 3 * self.line_height) self.num_font = f = QFont() f.setPixelSize(self.total_height) f.setItalic(True), f.setBold(True) f = QFontMetrics(f) self.num_ch = str(max(3, numeric_version[0])) self.footer_font = f = QFont() f.setPointSize(self.FOOTER_SIZE) f.setItalic(True) self.dpr = QApplication.instance().devicePixelRatio() self.pmap = QPixmap(I('library.png', allow_user_override=False)) self.pmap.setDevicePixelRatio(self.dpr) self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE), int(self.dpr * self.LOGO_SIZE), transformMode=Qt.SmoothTransformation) self.light_brush = QBrush(QColor('#F6F3E9')) self.dark_brush = QBrush(QColor('#39322B')) pmap = QPixmap(int(self.WIDTH * self.dpr), int(self.WIDTH * self.dpr)) pmap.setDevicePixelRatio(self.dpr) pmap.fill(Qt.transparent) QSplashScreen.__init__(self, pmap) self.setWindowTitle('Sistema Biblioteca Nacional') def drawContents(self, painter): self.drawn_once = True painter.save() painter.setRenderHint(painter.TextAntialiasing, True) painter.setRenderHint(painter.Antialiasing, True) pw = self.LOGO_SIZE height = max(pw, self.total_height) width = self.width() # Draw frame y = (self.height() - height) // 2 bottom = y + height painter.fillRect(0, y, width, height, self.light_brush) painter.fillRect(0, y, width, self.title_height, self.dark_brush) painter.fillRect(0, y, pw, height, self.dark_brush) dy = (height - self.LOGO_SIZE) // 2 painter.drawPixmap(0, y + dy, self.pmap) # Draw number painter.setFont(self.num_font) num_width = painter.boundingRect(0, 0, 0, 0, Qt.AlignCenter | Qt.TextSingleLine, '2018').width() + 12 num_x = width - num_width painter.setPen(QPen(QColor('#d6b865'))) painter.drawText(num_x, y, num_width, height, Qt.AlignCenter | Qt.TextSingleLine, '2018') # Draw title x = pw + 20 width -= num_width + 5 + x painter.setFont(self.title_font) painter.drawText(x, y, width, self.title_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, "Alan Beck - Federico Princich ") # Draw starting up message y += self.title_height + 5 painter.setPen(QPen(self.dark_brush.color())) painter.setFont(self.body_font) br = painter.drawText( x, y, width, self.line_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, _('Starting up, please wait...')) starting_up_bottom = br.bottom() # Draw footer m = self.message() if m and m.strip(): painter.setFont(self.footer_font) b = max(starting_up_bottom + 5, bottom - self.line_height) painter.drawText(x, b, width, self.line_height, Qt.AlignLeft | Qt.AlignTop | Qt.TextSingleLine, m) painter.restore() def show_message(self, msg): self.showMessage(msg) self.wait_for_draw() def wait_for_draw(self): # Without this the splash screen is not painted on linux and windows self.drawn_once = False st = monotonic() while not self.drawn_once and (monotonic() - st < 0.1): QApplication.instance().processEvents() def keyPressEvent(self, ev): if not self.develop: return QSplashScreen.keyPressEvent(self, ev) ev.accept() QApplication.instance().quit() def __init__(self, develop=False): #from calibre.gui2 import Application #app = Application([]) #app = QtWidgets.QApplication(sys.argv) #w = QtWidgets.QtWidget() #w.show() #app.exec_() self.inicio_splash()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.bright_value = str() self.correct_scale = str() self.path_2_image = str() self.is_eyes = str() self.is_eyeglasses = str() self.is_open = str() self.blured = str() self.blur_value = int() self.brightness_value = int() self.pixmap = QPixmap() self.pixmap_token = QPixmap() self.pixmap_logo = QPixmap() self.brightFlag = bool self.blurFlag = bool self.eyesFlag = bool self.eyes_openedFlag = bool self.scaleFlag = bool uic.loadUi('window.ui', self) self.pushButton.clicked.connect(self.browse_image) self.pushButton_2.clicked.connect(self.start_second_window) def start_second_window(self): self.open_second_window(self.path_2_image) def browse_image(self): self.textBrowser.clear() self.path_2_image = QFileDialog.getOpenFileName( self, 'Open File', './photo')[0] self.open_image_func() def open_second_window(self, path): show_info(path, self.blur_value, self.brightness_value) def open_image_func(self): self.open_image() def open_image(self): self.img = cv2.imread(self.path_2_image) frame = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) self.load_image() self.start(frame) def load_image(self): self.pixmap.load(self.path_2_image) pixmap = self.pixmap.scaled(461, 671) self.label.setPixmap(pixmap) def start(self, frame): flag, faces = face_detection(frame) self.eyeglasses_status(flag, faces, frame) self.is_blured() self.is_right_scale() self.is_bright() self.append_result() def eyeglasses_status(self, flag, faces, frame): if flag: self.eyesFlag = is_eye_exist(faces, frame) if self.eyesFlag: self.is_eyeglasses = '<font color="green">Нет</font>' self.is_eyes = '<font color="green">Видны</font>' self.close_open_eyes() else: self.is_eyeglasses = '<font color="green">Есть</font>' self.is_eyes = '<font color="red">Не видны</font>' self.is_open = '<font color="red">Не удалось определить</font>' def close_open_eyes(self): self.eyes_openedFlag = is_eyes_opened(self.img) if self.eyes_openedFlag: self.is_open = '<font color="green">Окрыты</font>' else: self.is_open = '<font color="red">Закрыты</font>' def is_blured(self): self.blurFlag, self.blur_value = is_blured(self.img) if self.blurFlag: self.blured = '<font color="red">Не соответствует</font>' else: self.blured = '<font color="green">Соответствует</font>' def is_right_scale(self): self.scaleFlag = is_ratio_correct(self.img) if self.scaleFlag: self.correct_scale = '<font color="green">Соответствует</font>' else: self.correct_scale = '<font color="red">Не соответсвует</font>' def is_bright(self): bright, light = is_too_bright(self.img) notbright, dark = is_not_bright(self.img) if bright: self.bright_value = '<font color="red">Избыток</font>' self.brightness_value = light self.brightFlag = False elif notbright: self.bright_value = '<font color="red">Недостаточно</font>' self.brightness_value = dark self.brightFlag = False else: self.bright_value = '<font color="green">Достаточно</font>' self.brightness_value = light self.brightFlag = True def access_token(self): green_token = './labels/green_gal.png' red_token = './labels/red_cross.png' if self.brightFlag and not self.blurFlag and self.eyesFlag and self.eyes_openedFlag and self.scaleFlag: self.pixmap_token.load(green_token) self.pixmap_token.scaled(191, 151) self.label_4.setPixmap(self.pixmap_token) else: self.pixmap_token.load(red_token) self.pixmap_token.scaled(191, 151) self.label_4.setPixmap(self.pixmap_token) def load_logo(self): self.pixmap_logo.load('./labels/unnamed.png') self.MyDocuments.setPixmap(self.pixmap_logo) def append_result(self): self.textBrowser.append( f'<h1>Наличие очков: {self.is_eyeglasses}</h1>' f'<h1>Глаза: {self.is_eyes}</h1>' f'<h1>Сотояние глаз: {self.is_open}' f'<h1>Фон: {self.blured}</h1>' f'<h1>Соотношение лица относительно фона: {self.correct_scale}</h1>' f'<h1>Свет в изображении: {self.bright_value}</h1>') self.access_token()
class PaintBoard(QWidget): def __init__(self): QWidget.__init__(self) # self.label = QLabel(self) # self.gridLayout = QGridLayout(self) # self.gridLayout.addWidget(self.label) self.pixmap = QPixmap(1,1) self.pixmap.fill(Qt.white) self.img = QImage(self.pixmap.toImage()) # self.label.setFrameShape(1) # # self.label.setPixmap(self.pixmap) # self.label.setScaledContents(True) # self.label.setVisible(False) self.pen = QPainter() def paintEvent(self, paintEvent): self.pixmap = self.pixmap.scaled(self.width(), self.height()) self.pen.begin(self) # self.pen.drawPixmap(0, 0, self.pixmap) self.img = QImage(self.pixmap.toImage()) self.pen.drawImage(0, 0, self.img) self.pen.end() def drawPoints(self, x, y): # print(self.width(),self.height()) m = int(self.width()/2) + x n = int(self.height()/2) - y self.pen.begin(self.pixmap) self.pen.setPen(QPen(Qt.black,1)) self.pen.drawPoint(m, n) self.pen.end() self.update() # self.repaint() def load_img(self, img): self.pixmap.load(img) self.update() #DDA def drawLine(self, x0, y0, x1, y1): self.Clear() dx = x1 - x0 dy = y1 - y0 if fabs(dx) > fabs(dy): steps = fabs(dx) else: steps = fabs(dy) self.drawPoints(int(x0+0.5), int(y0+0.5)) xInc = dx/steps yInc = dy/steps for i in range(int(steps+0.5)): x0 += xInc y0 += yInc self.drawPoints(int(x0+0.5), int(y0+0.5)) #中点法画圆 def CirclePlot(self, xc, yc, x, y): self.drawPoints(x+xc, y+yc) self.drawPoints(-x+xc, y+yc) self.drawPoints(x+xc, -y+yc) self.drawPoints(-x+xc, -y+yc) self.drawPoints(y+xc, x+yc) self.drawPoints(y+xc, -x+yc) self.drawPoints(-y+xc, x+yc) self.drawPoints(-y+xc, -x+yc) def drawRound(self, xc, yc, r): self.Clear() x = 0 y = r d = 3-2*r self.CirclePlot(xc, yc, x, y) while x<y: if d<0: d = d+4*x+6 else: d = d+4*(x-y)+10 y -= 1 x +=1 self.CirclePlot(xc, yc, x, y) ''' # 边界填充 def fill(self, x, y): w = int(self.width()/2) h = int(self.height()/2) block = deque([(x, y)]) while 1: if len(block) == 0: break else: # print(block) point = block.popleft() m = point[0] n = point[1] # c = self.img.pixel(w+m, h+n) # colors = QColor(c).getRgb() # if colors != (0, 0, 0, 255): self.drawPoints(m, n) # result.append((m,n)) c = self.img.pixel(w+m, h+n-1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n-1) not in block: block.append((m,n-1)) c = self.img.pixel(w+m, h+n+1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n+1) not in block: block.append((m,n+1)) c = self.img.pixel(w+m-1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m-1,n) not in block: block.append((m-1,n)) c = self.img.pixel(w+m+1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m+1,n) not in block: block.append((m+1,n)) print(results) ''' #边界填充 #种子边界填充 def fill(self, x, y): w = int(self.width()/2) h = int(self.height()/2) block = deque([(x, y)]) results = [] while 1: if len(block) == 0: break else: point = block.popleft() m = point[0] n = point[1] results.append((m,n)) c = self.img.pixel(w+m, h+n-1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n-1) not in block: if (m,n-1) not in results: block.append((m,n-1)) c = self.img.pixel(w+m, h+n+1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n+1) not in block: if (m,n+1) not in results: block.append((m,n+1)) c = self.img.pixel(w+m-1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m-1,n) not in block: if (m-1,n) not in results: block.append((m-1,n)) c = self.img.pixel(w+m+1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m+1,n) not in block: if (m+1,n) not in results: block.append((m+1,n)) for point in results: self.drawPoints(point[0], point[1]) def Clear(self): self.pixmap.fill(Qt.white) self.update()
def setimg(self, var, img): im = "icons\\" + img + ".png" im = QPixmap(im) im = im.scaled(64, 64) var.setPixmap(QPixmap(im))
def update_host(self, host_item=None): """ Update HostQWidget data and QLabels :param host_item: the Host item :type host_item: alignak_app.items.host.Host """ if self.host_item and not host_item: self.set_data(self.host_item) if host_item: self.set_data(host_item) if self.host_item or host_item: # Update host services self.refresh_counter += 1 if self.refresh_counter > 10: thread_manager.add_high_priority_thread( 'service', self.host_item.item_id) self.refresh_counter = 0 # Update host icon_name = get_overall_state_icon( self.service_items, self.host_item.data['_overall_state_id']) icon_pixmap = QPixmap(settings.get_image(icon_name)) self.labels['host_icon'].setPixmap(QPixmap(icon_pixmap)) self.labels['host_icon'].setToolTip( self.host_item.get_overall_tooltip(self.service_items)) self.labels['host_name'].setText('%s' % self.host_item.get_display_name()) monitored = self.host_item.data[ 'passive_checks_enabled'] + self.host_item.data[ 'active_checks_enabled'] icon_name = get_icon_name('host', self.host_item.data['ls_state'], self.host_item.data['ls_acknowledged'], self.host_item.data['ls_downtimed'], monitored) pixmap_icon = QPixmap(settings.get_image(icon_name)) final_icon = pixmap_icon.scaled(32, 32, Qt.KeepAspectRatio) self.labels['state_icon'].setPixmap(final_icon) self.labels['state_icon'].setToolTip(self.host_item.get_tooltip()) since_last_check = get_diff_since_last_timestamp( self.host_item.data['ls_last_check']) last_check_tooltip = get_date_fromtimestamp( self.host_item.data['ls_last_check']) self.labels['ls_last_check'].setText(since_last_check) self.labels['ls_last_check'].setToolTip(last_check_tooltip) self.labels['ls_output'].setText(self.host_item.data['ls_output']) self.labels['realm'].setText( data_manager.get_realm_name(self.host_item.data['_realm'])) self.labels['address'].setText(self.host_item.data['address']) self.labels['business_impact'].setText( str(self.host_item.data['business_impact'])) self.labels['notes'].setText(self.host_item.data['notes']) self.actions_widget.item = self.host_item self.actions_widget.update_widget() self.activecheck_btn.update_btn_state( self.host_item.data['active_checks_enabled']) self.passivecheck_btn.update_btn_state( self.host_item.data['passive_checks_enabled']) self.customs_btn.setEnabled(bool(self.host_item.data['customs'])) # Update host history self.host_history = data_manager.get_item('history', self.host_item.item_id) if self.host_history: self.history_btn.setEnabled(True) self.history_btn.setToolTip(_('History is available')) else: self.history_btn.setToolTip( _('History is not available, please wait...')) self.history_btn.setEnabled(False) if app_backend.connected: thread_manager.add_high_priority_thread( 'history', { 'hostname': self.host_item.name, 'host_id': self.host_item.item_id }) else: thread_manager.stop_threads()