我正在尝试使用Pyqt5
. 最好在 GUI 中选择图像,以便用户可以立即轻松地选择和复制该图像。
通过“可选”,我的意思是用户可以右键单击图像,然后复制它,然后可能将其粘贴到 GUI 之外的其他地方。就像保存在 Word 中的普通图像一样。用户可以在 Word 中选择/复制图像,然后将其粘贴到其他地方。
我知道 Text 在Qlabel
这可以很容易地通过使用self.my_label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
. 但是,对于图像,似乎没有这样的方法来处理它。有什么办法可以解决图像问题吗?
import sys
import PyQt5
from PyQt5.QtWidgets import (
QLabel,
QVBoxLayout,
QWidget
)
from PyQt5 import QtCore
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QSize
class Display_Window(QWidget):
def __init__(self):
super().__init__()
self.setMinimumSize(QSize(980,700))
self.layout = QVBoxLayout(self)
self.label1 = QLabel(self)
self.pixmap = QPixmap(path_to_my_image)
self.pixmap = self.pixmap.scaled(900, 900, QtCore.Qt.KeepAspectRatio)
self.label1.setPixmap(self.pixmap)
self.label1.resize(self.pixmap.width(), self.pixmap.height())
# Run if Script
if __name__ == "__main__":
app = PyQt5.QtWidgets.QApplication(sys.argv)
MainWindow = Display_Window() # Initialize GUI
MainWindow.show() # Show Window
app.exec_()
您可以将标签子类化并在它具有有效像素图时创建菜单,然后使用系统剪贴板复制它。
class CopiableLabel(QLabel):
def contextMenuEvent(self, event):
pixmap = self.pixmap()
if not pixmap.isNull():
menu = QMenu()
copyAction = menu.addAction('Copy image to clipboard')
if menu.exec_(event.globalPos()) == copyAction:
QApplication.clipboard().setPixmap(pixmap)
return
super().contextMenuEvent(event)
class Display_Window(QWidget):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout(self)
self.label1 = CopiableLabel(self)
self.layout.addWidget(self.label1)
self.pixmap = QPixmap(path_to_my_image)
self.pixmap = self.pixmap.scaled(900, 900, Qt.KeepAspectRatio)
self.label1.setPixmap(self.pixmap)
请注意,在 QLabel 上设置像素图会自动调整其大小(除非它的scaledContents
属性设置为True
。
您还应该将标签添加到布局中,就像我在上述修改中所做的那样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句