[英]QPixmap maintain aspect ratio
我正在編寫一個程序,允許我通過他們的 API 將照片上傳到 TUMBLR,我已經開始上傳(感謝你們)。
我在 GUI 的一側放了一個“queueBox”,它顯示圖像名稱,它們存儲在 QListWidget 中。 我已經把它放在我的主類的構造函數中:
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setupUi(self)
self.queueBox.itemClicked.connect(self.displayPhoto)
我有這個方法:
def displayPhoto(self, item):
tempName = (item.text())
print tempName
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)))
## self.myLabel.pixmap(QPixmap.scaled(aspectRatioMode = Qt.IgnoreAspectRatio))
## ^ ^ ^ What do I do with this? How do I set it to maintain aspect ratio?
## Currently it says ''NameError: global name 'Qt' is not defined''
這成功地將圖像繪制到 myLabel 上,這是一個 QLabel,但是,它非常縮放,我有
self.myLabel.setScaledContents(True)
在我的 ui_mainWindow 類中,如果我將它設置為 False,它會修復縮放,但它只顯示圖像的一小部分,因為圖像比 QLabel 大得多。 我想要的是能夠保持縱橫比,所以它看起來不縮放和可怕。
我發現了這個: http : //www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qpixmap.html並說明了如何使用它,但是我無法如上面的代碼所示那樣工作在我的評論中。 有誰知道如何使用這個? 如果是這樣,你能給我提供一個例子嗎,我已經嘗試過搜索,但我得到的大部分結果都是用 C++ 編寫的,而不是 python。
謝謝!
擺脫
self.myLabel.setScaledContents(True)
調用(或將其設置為 False)。 它用像素圖填充您的小部件,而不關心縱橫比。
如果您需要調整QPixmap
大小,如您QPixmap
, scaled
是必需的方法。 但是你調用它是錯誤的。 我們來看看定義:
QPixmap QPixmap.scaled (self,
int width,
int height,
Qt.AspectRatioMode aspectRatioMode = Qt.IgnoreAspectRatio,
Qt.TransformationMode transformMode = Qt.FastTransformation)
此函數的返回類型是QPixmap
,因此它返回原始像素圖的縮放副本。
然后你需要一個width
和一個height
,描述像素圖的(最大)最終尺寸。
還有兩個可選參數。 aspectRatioMode
處理寬高比。 該文檔詳細介紹了不同的選項及其效果。 transformMode
定義了縮放的方式(哪種算法)。 它可能會改變圖像的最終質量。 你可能不需要這個。
所以,把它放在一起你應該有( Qt
命名空間在QtCore
):
# substitute the width and height to desired values
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)).scaled(width, height, QtCore.Qt.KeepAspectRatio))
或者,如果您有固定大小的QLabel
,則可以調用.size()
方法從中獲取大小:
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)).scaled(self.myLabel.size(), QtCore.Qt.KeepAspectRatio))
注意:您可能希望將os.path.join(directory, tempName)
用於directory + '\\\\' + tempName
部分。
PyQt5 代碼更改更新:
上述答案阿瓦里斯需要PyQt5更新,因為它打破。
QPixmap.scaled (self, int width, int height, Qt.AspectRatioMode aspectRatioMode = Qt.IgnoreAspectRatio
將self
保留在代碼中會導致以下回溯錯誤。
類型錯誤:參數與任何重載調用不匹配:scaled(self,int,int,aspectRatioMode:Qt.AspectRatioMode = Qt.IgnoreAspectRatio,transformMode:Qt.TransformationMode = Qt.FastTransformation):參數1具有意外類型'MainUI' scaled(self , QSize, aspectRatioMode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode = Qt.FastTransformation): 參數 1 具有意外類型“MainUI”
因此這應該是(沒有“self”,“Qt”)如下所述:
QPixmap.scaled (int width, int height, aspectRatioMode = IgnoreAspectRatio
要么:
QPixmap.scaled (int width, int height, aspectRatioMode = 0)
KeepAspectRatio = 2... 但在上面代碼中由aspectRatioMode = 2
提供。 享受!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.