ここでは本当に新しいことは何もありません。
受け入れられた返信
https://stackoverflow.com/a/8212120/11413792
と
https://stackoverflow.com/a/43936590/11413792
を使用して混合しましsetContentsMargins
たが、少し独自の方法でコーディングしました。
/**
* @brief calcMargins Calculate the margins when a rectangle of one size is centred inside another
* @param outside - the size of the surrounding rectanle
* @param inside - the size of the surrounded rectangle
* @return the size of the four margins, as a QMargins
*/
QMargins calcMargins(QSize const outside, QSize const inside)
{
int left = (outside.width()-inside.width())/2;
int top = (outside.height()-inside.height())/2;
int right = outside.width()-(inside.width()+left);
int bottom = outside.height()-(inside.height()+top);
QMargins margins(left, top, right, bottom);
return margins;
}
関数は、ある長方形を別の長方形の中央に配置するために必要なマージンを計算します。何がわからないのですが、いろいろなことに使えるかなり汎用的な機能です。
その後setContentsMargins
、多くの人が1つに結合する2つの余分な行で使いやすくなります。
QPixmap scaled = p.scaled(this->size(), Qt::KeepAspectRatio);
QMargins margins = calcMargins(this->size(), scaled.size());
this->setContentsMargins(margins);
setPixmap(scaled);
それは誰かに興味があるかもしれません...私は処理mousePressEvent
し、画像内のどこにいるかを知る必要がありました。
void MyClass::mousePressEvent(QMouseEvent *ev)
{
QMargins margins = contentsMargins();
QPoint labelCoordinateClickPos = ev->pos();
QPoint pixmapCoordinateClickedPos = labelCoordinateClickPos - QPoint(margins.left(),margins.top());
... more stuff here
}
私の大きな画像はカメラからのものであり、ピックスマップの幅で割ってから元の画像の幅を掛けることによって相対座標[0、1)を取得しました。