在qml中,我可以簡單地這樣做
Image {
anchors.fill: parent
source: "/path/to/coo/image"/span>
fillMode: Image.PreserveAspectFit
}
由于QML與JavaScript的聯系,我不想使用它。 我怎樣才能用Widgets做到這一點呢?
我嘗試使用QLabel,但是它沒有設定長寬比或填充模式的選項。我想我可以手動縮放像素圖,然后將其設定為QLabel,但這不會像QML那樣是反應式的(當視窗調整大小時調整影像大小)。難道Qt中沒有任何影像專用的部件來做這個嗎?
uj5u.com熱心網友回復:
你可以簡單地這樣做:
QPixmap pixmap("background.png")。
pixmap.scaled(pixmap.size(), Qt::KeepAspectRatio) 。
你可以隨心所欲地操縱尺寸值。如果你想的話,你可以捕捉到像素圖所在的QLabel的大小。
uj5u.com熱心網友回復:
一個可能的解決方案是使用QGraphicsView、QGraphicsScene和QGraphicsPixmapItem:
#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QPixmap>/span>
class Viewer。public QGraphicsView{
public:
Viewer(QWidget *parent = nullptr)。QGraphicsView(parent){
setScene(new QGraphicsScene(this) )。)
m_pixmapItem = scene()->addPixmap(QPixmap)。
setAlignment(Qt::AlignCenter)。
}
QPixmap pixmap() const{
return m_pixmapItem->pixmap()。
}
void setPixmap(const QPixmap &newPixmap){
m_pixmapItem->setPixmap(newPixmap)。
fitInView(m_pixmapItem, Qt::KeepAspectRatio) 。
}
protected:
void resizeEvent(QResizeEvent *event){
QGraphicsView::resizeEvent(event)。
fitInView(m_pixmapItem, Qt::KeepAspectRatio) 。
}
private:
QGraphicsPixmapItem *m_pixmapItem。
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv)。
QPixmap pixmap(100, 200)。
pixmap.fill(Qt::green)。
瀏覽器w;
w.resize(640, 480)。
w.setPixmap(pixmap)。
w.show()。
return a.exec()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310162.html
標籤:
