# 以下函数是写在 class 定义外的 def_get_widget_size(widget: QWidget): """ return specific widget width and height minus 15 because the right side is narrower 获取 Widget 的宽和高,这里 - 15是为了让图片右边留出与左边差不多大的空隙,否则 显示出来的效果是左边有一段空隙右边没有,视觉上不对称。此数值可以自由调整 :return: """ return widget.width() - 15, widget.height() - 15
def_calculate_child_size(parent_size: tuple, child_size: tuple, hw_flag: bool): """ calculate child size base on its parent size to make it central :type hw_flag: bool, if child_height == parent_height, True; otherwise False :param parent_size: (width, height) :param child_size: (width, height), child old size :return: 通过 hw_flag 判断情况,并计算出缩放后的 Label 即图像的大小 """ if hw_flag: child_height = parent_size[1] child_width = child_height * child_size[0] / child_size[1] else: child_width = parent_size[0] child_height = child_width * child_size[1] / child_size[0] return child_width, child_height
def_determine_hw_flag(parent_size: tuple, child_size: tuple): """ determine hw flag. If child_height == parent_height, True; otherwise False :param parent_size: (width, height) :param child_size: (width, height) :return: bool 通过 宽高比 判断属于哪一种情况 """ if (child_size[1] / child_size[0]) > (parent_size[1] / parent_size[0]): returnTrue else: returnFalse # 以下函数是 class 的函数 defdisplay_image(self): """ read picture file and display it :return: """ # 读取图片 pixmap = QPixmap(self.file_path) # we need to let picture show correctly pixmap_width = pixmap.width() pixmap_height = pixmap.height() # 这里首先记录一下图片的原始大小,方便后续动态调整大小。 self.picture_size = (pixmap_width, pixmap_height) widget_width, widget_height = _get_widget_size(self.ui.imageWidget) move_flag = _determine_hw_flag((widget_width, widget_height), (pixmap_width, pixmap_height)) image_width, image_height = _calculate_child_size((widget_width, widget_height), (pixmap_width, pixmap_height), move_flag) self.ui.imageLabel.setPixmap(pixmap) self.ui.imageLabel.resize(int(image_width), int(image_height)) # 设置图片自适应 Label self.ui.imageLabel.setScaledContents(True) self.ui.imageLabel.setAlignment(Qt.AlignCenter) # 这一行似乎没有用,去掉也可以 # we need to move Label to the center of widget # 现在需要将 Label 移动到 Widget 的正中间,move_flag 即 hw_flag,若上下留白则上下移动,否则左右移动 if move_flag: step_length = int((widget_width - (10 + image_width)) / 2) self.ui.imageLabel.move(10 + step_length, 10) else: step_length = int((widget_height - (10 + image_height)) / 2) self.ui.imageLabel.move(10, 10 + step_length) definit_action(self): """ bind function to slot 将 select_file 函数与 button 绑定,这样点击 button 之后就会触发函数进行执行。 :return: """ self.ui.selectButton.clicked.connect(self.select_file)
Comments