Python源码示例:PyQt5.QtCore.Qt.KeepAspectRatio()
示例1
def _paint_frame(self, event):
if self.bgimage:
pixmap = self._build_pixmap(self.bgimage)
# Check we need to resize the bgimage
if self.bgsize:
bgsize = self.bgsize
if self.bgsize == 'fit':
bgsize = self.size()
pixmap = pixmap.scaled(bgsize, Qt.KeepAspectRatio, Qt.SmoothTransformation)
# Calculate the x,y position
x,y = self.bgpos
if self.bgpos:
if x == 'left': x = 0
elif x == 'center': x = (self.width() / 2) - (pixmap.width() / 2)
elif x == 'right': x = self.width() - pixmap.width()
if y == 'top': y = 0
elif y == 'center': y = (self.height() / 2) - (pixmap.height() / 2)
elif y == 'bottom': y = self.height() - pixmap.height()
# Draw the pixmap
painter = QtGui.QPainter(self)
painter.setOpacity(self.bgopacity)
painter.drawPixmap(int(x), int(y), pixmap)
示例2
def set_status(self, raw, exist=None):
item = QLabel()
item.setAlignment(Qt.AlignCenter)
if exist is 0:
icon = QPixmap(QUEUE_ICON).scaled(20, 20, Qt.KeepAspectRatio,
Qt.SmoothTransformation)
item.setPixmap(icon)
item.setToolTip('Waiting in the download queue...')
if exist is 1:
icon = QPixmap(CHECK_ICON).scaled(20, 20, Qt.KeepAspectRatio,
Qt.SmoothTransformation)
item.setPixmap(icon)
item.setToolTip('All the features are downloaded...')
if exist is 2:
item = QPushButton(self)
item.setToolTip('Download')
item.setIcon(QIcon(DOWNLOAD_ICON))
item.clicked.connect(self.download_clicked)
self.setCellWidget(raw, 0, item)
示例3
def __init__(self,parent="None",title="None",description="None",url="None",urlImage="None"):
super(Tiles,self).__init__()
#Heading Widget
self.heading = QLabel('<b>%s</b>'%title)
#SubHeading Widget with link to open in browser
self.subHeading = QLabel('{}<a href="{}">...more</a>'.format(description,url))
self.subHeading.setOpenExternalLinks(True)
#Image Widget with article
try:
data = urllib.request.urlopen(urlImage).read()
except:
data = urllib.request.urlopen("https://ibb.co/XY30sjs").read()
self.image = QImage()
self.image.loadFromData(data)
self.imageLabel = QLabel("image")
self.imageLabel.setPixmap(QPixmap(self.image).scaled(64,64,Qt.KeepAspectRatio))
self.tileLayout = QGridLayout()
self.tileLayout.addWidget(self.heading,1,0)
self.tileLayout.addWidget(self.imageLabel,1,1)
self.tileLayout.addWidget(self.subHeading,2,0)
示例4
def paintEvent(self, event):
ancho, altura = self.width(), self.height()
icono = self.icono.scaled(ancho, altura, Qt.KeepAspectRatio, Qt.SmoothTransformation)
pintor = QPainter()
pintor.begin(self)
pintor.setRenderHint(QPainter.Antialiasing, True)
pintor.setPen(Qt.NoPen)
pintor.drawPixmap(0, 0, icono, 0, 0, 0, 0)
pintor.setPen(Qt.white)
pintor.drawText(event.rect(), Qt.AlignCenter, self.etiqueta)
pintor.setPen(Qt.NoPen)
pintor.setBrush(self.opacidad)
pintor.drawEllipse(0, 0, ancho, altura)
pintor.end()
self.setMask(icono.mask())
示例5
def initUI(self):
label = QLabel(self)
label.setPixmap(QPixmap("Imagenes/siacle.jpg").scaled(450, 450, Qt.KeepAspectRatio,
Qt.SmoothTransformation))
label.move(0, 0)
botonCerrar = QPushButton("Cerrar", self)
botonCerrar.setFixedSize(430, 32)
botonCerrar.move(10, 457)
# ========================= EVENTO =========================
botonCerrar.clicked.connect(self.close)
# ========================= CLASE Acerca ===========================
示例6
def initUI(self):
label = QLabel(self)
label.setPixmap(QPixmap("Imagenes/siacle.jpg").scaled(450, 450, Qt.KeepAspectRatio,
Qt.SmoothTransformation))
label.move(0, 0)
labelAcerca = QLabel("SIACLE: sistema para administrar clientes, diseñado y\n"
"desarrollado por ANDRES NIÑO con fines educativos.", self)
labelAcerca.move(10, 460)
botonCerrar = QPushButton("Cerrar", self)
botonCerrar.setFixedSize(80, 32)
botonCerrar.move(360, 457)
# ========================= EVENTO =========================
botonCerrar.clicked.connect(self.close)
# ========================= CLASE Siacle ===========================
示例7
def initUI(self):
# ==================== WIDGET QLABEL =======================
self.labelImagen = QLabelClickable(self)
self.labelImagen.setGeometry(15, 15, 118, 130)
self.labelImagen.setToolTip("Imagen")
self.labelImagen.setCursor(Qt.PointingHandCursor)
self.labelImagen.setStyleSheet("QLabel {background-color: white; border: 1px solid "
"#01DFD7; border-radius: 5px;}")
self.pixmapImagen = QPixmap("Qt.png").scaled(112, 128, Qt.KeepAspectRatio,
Qt.SmoothTransformation)
self.labelImagen.setPixmap(self.pixmapImagen)
self.labelImagen.setAlignment(Qt.AlignCenter)
# ===================== EVENTO QLABEL ======================
# Llamar función al hacer clic o doble clic sobre el label
self.labelImagen.clicked.connect(self.Clic)
# ======================= FUNCIONES ============================
示例8
def _fit_in_view(view, rect, flags=Qt.IgnoreAspectRatio):
if view.scene() is None or rect.isNull():
return
view.last_scene_roi = rect
unity = view.transform().mapRect(QRectF(0, 0, 1, 1))
view.scale(1 / unity.width(), 1 / unity.height())
view_rect = view.viewport().rect()
scene_rect = view.transform().mapRect(rect)
xratio = view_rect.width() / scene_rect.width()
yratio = view_rect.height() / scene_rect.height()
if flags == Qt.KeepAspectRatio:
xratio = yratio = min(xratio, yratio)
elif flags == Qt.KeepAspectRatioByExpanding:
xratio = yratio = max(xratio, yratio)
view.scale(xratio, yratio)
view.centerOn(rect.center())
# name must match because we're overriding QMainWindow method
示例9
def paint(self, painter, option, index):
column = index.column()
if column == 1:
pixmap = None
status = index.data(Qt.UserRole)
if status == MagicFolderChecker.LOADING:
self.waiting_movie.setPaused(False)
pixmap = self.waiting_movie.currentPixmap().scaled(
20, 20, Qt.KeepAspectRatio, Qt.SmoothTransformation
)
elif status in (
MagicFolderChecker.SYNCING,
MagicFolderChecker.SCANNING,
):
self.sync_movie.setPaused(False)
pixmap = self.sync_movie.currentPixmap().scaled(
20, 20, Qt.KeepAspectRatio, Qt.SmoothTransformation
)
if pixmap:
point = option.rect.topLeft()
painter.drawPixmap(QPoint(point.x(), point.y() + 5), pixmap)
option.rect = option.rect.translated(pixmap.width(), 0)
super(Delegate, self).paint(painter, option, index)
示例10
def updateImage(self, opencv_rgb_image):
self.cv_img_rgb = opencv_rgb_image
height, width, channel = self.cv_img_rgb.shape
bytesPerLine = 3 * width
self.q_image = QImage(self.cv_img_rgb.data, width,
height, bytesPerLine, QImage.Format_RGB888)
# self.QPixmap=QPixmap.fromImage(self.q_image)
# scaredPixmap = self.QPixmap.scaled(self,self.frame_lbl.frameSize, aspectRatioMode=Qt.IgnoreAspectRatio)
self.frame_lbl.setPixmap(QPixmap.fromImage(self.q_image).scaled(self.frame_lbl.size(), aspectRatioMode=Qt.KeepAspectRatio))
示例11
def reset_view(self):
# The SceneRect controls how far you can pan, make it larger than
# just the bounding box so middle-click panning works
panning_rect = QRectF(self.scene_bounding_rect)
panning_rect_center = panning_rect.center()
panning_rect_size = max(panning_rect.width(), panning_rect.height())*3
panning_rect.setSize(QSizeF(panning_rect_size, panning_rect_size))
panning_rect.moveCenter(panning_rect_center)
self.setSceneRect(panning_rect)
self.fitInView(self.scene_bounding_rect, Qt.KeepAspectRatio)
self.zoom_view(0.8)
self.update_grid()
示例12
def update_preview(self):
if not self._preview_pixmap:
return
scaled = self._preview_pixmap.scaled(
self._ui.lblPreview.width(),
self._ui.lblPreview.height(),
Qt.KeepAspectRatio,
Qt.SmoothTransformation,
)
self._ui.lblPreview.setPixmap(scaled)
示例13
def run(self):
cap = cv2.VideoCapture(0)
fps_update_cnt = 0
fps_update_num = 10
while True:
display_time = time.time()
ret, x_np = cap.read()
x_np = cv2.cvtColor(x_np, cv2.COLOR_BGR2RGB)
y_np, inference_time = self.transfer(x_np)
x_qt = QImage(x_np.data, x_np.shape[1], x_np.shape[0], QImage.Format_RGB888)
x_qt = QPixmap.fromImage(x_qt)
x_qt = x_qt.scaled(self.video_width, self.video_height, Qt.KeepAspectRatio)
y_qt = QImage(y_np.data, y_np.shape[1], y_np.shape[0], QImage.Format_RGB888)
y_qt = QPixmap.fromImage(y_qt)
y_qt = y_qt.scaled(self.video_width, self.video_height, Qt.KeepAspectRatio)
self.change_pixmap_x.emit(x_qt)
self.change_pixmap_y.emit(y_qt)
fps_update_cnt = (fps_update_cnt + 1) % fps_update_num
if fps_update_cnt == 0:
self.change_pixmap_inf.emit(' Infrence FPS: {0:.2f}'.format(
1 / inference_time if inference_time is not None else 0))
display_time = time.time() - display_time
self.change_pixmap_dis.emit(' Display FPS: {0:.2f}'.format(1 / display_time))
示例14
def _draw_pixmap(self, source, selected, synced):
color = QColor(0x33, 0x33, 0x33) if selected else QColor(0x99, 0x99, 0x99)
p = Pixmap(source)
if p.isNull():
return
p = Pixmap(p.scaled(120, 120, Qt.KeepAspectRatio))
p.replace_color(QColor(0, 0, 0), color)
painter = QPainter(p)
if synced:
painter.drawPixmap(p.width() - 90, 0, 100, 100, IconTableItem.SYNCED_ICON)
else:
painter.drawPixmap(p.width() - 90, 0, 100, 100, IconTableItem.UNSYNCED_ICON)
painter.end()
return p
示例15
def seleccionarImagen(self):
imagen, extension = QFileDialog.getOpenFileName(self, "Seleccionar imagen", getcwd(),
"Archivos de imagen (*.png *.jpg)",
options=QFileDialog.Options())
if imagen:
# Adaptar imagen
pixmapImagen = QPixmap(imagen).scaled(166, 178, Qt.KeepAspectRatio,
Qt.SmoothTransformation)
# Mostrar imagen
self.labelImagen.setPixmap(pixmapImagen)
示例16
def initUI(self):
# ===================== WIDGET QLABEL ======================
label = QLabel(self)
label.setGeometry(20, 20, 100, 100)
label.setPixmap(QPixmap(":imagenes/Python.png").scaled(100, 100, Qt.KeepAspectRatio,
Qt.SmoothTransformation))
# ================================================================
示例17
def seleccionarImagen(self):
imagen, extension = QFileDialog.getOpenFileName(self, "Seleccionar imagen", getcwd(),
"Archivos de imagen (*.png *.jpg)",
options=QFileDialog.Options())
if imagen:
# Adaptar imagen
pixmapImagen = QPixmap(imagen).scaled(112, 128, Qt.KeepAspectRatio,
Qt.SmoothTransformation)
# Mostrar imagen
self.labelImagen.setPixmap(pixmapImagen)
# ================================================================
示例18
def seleccionarImagen(self):
imagen, extension = QFileDialog.getOpenFileName(self, "Seleccionar imagen", getcwd(),
"Archivos de imagen (*.png *.jpg)",
options=QFileDialog.Options())
if imagen:
# Adaptar imagen
pixmapImagen = QPixmap(imagen).scaled(166, 178, Qt.KeepAspectRatio,
Qt.SmoothTransformation)
# Mostrar imagen
self.labelImagen.setPixmap(pixmapImagen)
示例19
def show_exp_pix(self):
if self.src_pix.width() > 0:
w = self.SrcImgShowLabel.width()
h = self.SrcImgShowLabel.height()
self.SrcImgShowLabel.setPixmap(self.src_pix.scaled(w, h, Qt.KeepAspectRatio))
if self.dst_pix.width() > 0:
w = self.DstImgShowLabel.width()
h = self.DstImgShowLabel.height()
self.DstImgShowLabel.setPixmap(self.dst_pix.scaled(w, h, Qt.KeepAspectRatio))
# 窗口大小变化,使显示内容适应窗口大小
示例20
def __init__(self):
QGraphicsView.__init__(self)
# Image is displayed as a QPixmap in a QGraphicsScene attached to this QGraphicsView.
self.scene = QGraphicsScene()
self.setScene(self.scene)
# Store a local handle to the scene's current image pixmap.
self._pixmapHandle = None
# Image aspect ratio mode.
# !!! ONLY applies to full image. Aspect ratio is always ignored when zooming.
# Qt.IgnoreAspectRatio: Scale image to fit viewport.
# Qt.KeepAspectRatio: Scale image to fit inside viewport, preserving aspect ratio.
# Qt.KeepAspectRatioByExpanding: Scale image to fill the viewport, preserving aspect ratio.
self.aspectRatioMode = Qt.KeepAspectRatio
# Scroll bar behaviour.
# Qt.ScrollBarAlwaysOff: Never shows a scroll bar.
# Qt.ScrollBarAlwaysOn: Always shows a scroll bar.
# Qt.ScrollBarAsNeeded: Shows a scroll bar only when zoomed.
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
# Stack of QRectF zoom boxes in scene coordinates.
self.zoomStack = []
# Flags for enabling/disabling mouse interaction.
self.canZoom = True
self.canPan = True
示例21
def mousePressEvent(self, event):
# retrieve the label
child = self.childAt(event.pos())
if not child:
return
self.controller.mode = 'selection'
# update the creation mode to the appropriate subtype
self.controller.creation_mode = child.subtype
pixmap = QPixmap(child.pixmap().scaled(
QSize(50, 50),
Qt.KeepAspectRatio,
Qt.SmoothTransformation
))
mime_data = QtCore.QMimeData()
mime_data.setData('application/x-dnditemdata', QtCore.QByteArray())
drag = QtGui.QDrag(self)
drag.setMimeData(mime_data)
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos() - child.pos() + QPoint(-3, -10))
if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
child.close()
else:
child.show()
示例22
def mousePressEvent(self, event):
# retrieve the label
child = self.childAt(event.pos())
if not child:
return
self.controller.mode = 'selection'
# update the creation mode to the appropriate subtype
self.controller.creation_mode = child.subtype
pixmap = QPixmap(child.pixmap().scaled(
QSize(50, 50),
Qt.KeepAspectRatio,
Qt.SmoothTransformation
))
mime_data = QtCore.QMimeData()
mime_data.setData('application/x-dnditemdata', QtCore.QByteArray())
drag = QtGui.QDrag(self)
drag.setMimeData(mime_data)
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos() - child.pos() + QPoint(-3, -10))
if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
child.close()
else:
child.show()
示例23
def mousePressEvent(self, event):
# retrieve the label
child = self.childAt(event.pos())
if not child:
return
self.controller.mode = 'selection'
# update the creation mode to the appropriate subtype
self.controller.creation_mode = child.subtype
# we change the view if necessary:
# if it is a site, we switch the site view
# if it is anything else and we are in the site view, we switch
# to the network view
if child.subtype == 'site':
self.project.show_site_view()
else:
if self.project.view_type == 'site':
self.project.show_network_view()
pixmap = QPixmap(child.pixmap().scaled(
QSize(50, 50),
Qt.KeepAspectRatio,
Qt.SmoothTransformation
))
mime_data = QtCore.QMimeData()
mime_data.setData('application/x-dnditemdata', QtCore.QByteArray())
drag = QtGui.QDrag(self)
drag.setMimeData(mime_data)
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos() - child.pos() + QPoint(-3, -10))
if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
child.close()
else:
child.show()
示例24
def _updateROI(self, roi):
if self.frame_data is None or not self.worm_index_type:
# no trajectories data presented, nothing to do here
roi.wormCanvas.clear()
return
self.updateROIcomboBox(roi)
# extract individual worm ROI
good = self.frame_data[self.worm_index_type] == roi.worm_index
row_data = self.frame_data.loc[good].squeeze()
if row_data.size == 0 or \
np.isnan(row_data['coord_x']) or \
np.isnan(row_data['coord_y']):
# invalid data nothing to do here
roi.wormCanvas.clear()
return
worm_img, roi_corner = getWormROI(self.frame_img,
row_data['coord_x'],
row_data['coord_y'],
row_data['roi_size']
)
roi_ori_size = worm_img.shape
worm_img = np.ascontiguousarray(worm_img)
worm_qimg = self._convert2Qimg(worm_img)
canvas_size = min(roi.wormCanvas.height(), roi.wormCanvas.width())
worm_qimg = worm_qimg.scaled(
canvas_size, canvas_size, Qt.KeepAspectRatio)
worm_qimg = self.drawSkelResult(worm_img, worm_qimg, row_data, roi.isDrawSkel, roi_corner, read_center=False)
pixmap = QPixmap.fromImage(worm_qimg)
roi.wormCanvas.setPixmap(pixmap)
示例25
def alterPixmap(self, pixmap=None):
#placeholder element accesc this function
if pixmap:
self.pixmap = pixmap
self.label.setStyleSheet('#label { background-color: #636363;\
border: 3px solid #ff5900; border-radius: 20px; }')
self.label.setPixmap(self.pixmap.scaled(160, 80, Qt.KeepAspectRatio))
示例26
def _update_view_with_image(view, image_array):
image = cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB)
height, width, _ = image.shape
bytes_per_line = 3 * width
qimg = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888)
view.scene().items()[0].setPixmap(QPixmap.fromImage(qimg))
PUBGISMainWindow._fit_in_view(view,
view.scene().itemsBoundingRect(),
flags=Qt.KeepAspectRatio)
示例27
def rescale(self):
self.scene.setSceneRect(self.scene.itemsBoundingRect())
self.ui.tabCrossSection.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
示例28
def __init__(self, resource_filename, size=None):
super().__init__(resource(resource_filename))
if size:
self.swap(
self.scaled(
size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation
)
)
示例29
def set_icon(self, fname):
# 打开 PDF
doc = fitz.open(fname)
# 加载封面
page = doc.loadPage(0)
# 生成封面图像
cover = render_pdf_page(page)
label = QLabel(self)
label.resize(self.width, self.width * 4 // 3)
# 设置图片自动填充 label
label.setScaledContents(True)
# 设置封面图片
p = QPixmap(cover)
p.scaled(self.width, self.width * 4 // 3, Qt.KeepAspectRatio)
label.setPixmap(p)
# 设置单元格元素为 label
self.table.setCellWidget(self.x, self.y, label)
# 删除 label 对象,防止后期无法即时刷新界面
# 因为 label 的生存周期未结束
del label
# 设置当前行数与列数
self.crow, self.ccol = self.x, self.y
# 每 8 个元素换行
if (not self.y % 7) and (self.y):
self.x += 1
self.y = 0
else:
self.y += 1