画像を表示するウィンドウを開くqtアプリケーションがあります。ウィンドウのサイズを変更して、ウィンドウのアスペクト比を維持できるようにしたい。ウィンドウの元のサイズは480x640(幅x高さ)です。幅を変えると高さも一緒に変え、高さを変えると幅も変えるという効果が欲しいです。ウィンドウの幅または高さを変更しているかどうかをどのように検出できますか。
以下のコードを実装しました。幅を変更してもアスペクト比は維持されますが、ウィンドウの高さを変更することはできません。高さを小さくしたり大きくしたりすることはできません。
以下のコードはウィンドウを作成します。
#ifndef VideoWidget_h
#define VideoWidget_h
#include <iostream>
// Qt libraries
#include <QApplication>
#include <QtCore>
#include <QWidget>
#include <QGLWidget>
using namespace cv;
using namespace std;
class VideoWidget : public QGLWidget
{
Q_OBJECT
public:
VideoWidget()
{
}
protected:
void resizeGL(int width, int height)
{
const float ASPECT_RATIO = (float) WIDTH / (float) HEIGHT;
const float aspect_ratio = (float) width / (float) height;
if (aspect_ratio > ASPECT_RATIO) {
height = (1.f / ASPECT_RATIO) * width;
resize(width, height);
} else if (aspect_ratio < ASPECT_RATIO) {
height = ASPECT_RATIO * height;
resize(width, height);
}
}
private:
int WIDTH = 480;
int HEIGHT = 640;
};
#endif /* VideoWidget_h */
以下のコードが主な機能です。
#include <iostream>
// Qt libraries
#include <QApplication>
#include <QtCore>
#include <QWidget>
#include <QGLWidget>
#include "VideoWidget.h"
using namespace cv;
using namespace std;
int main(int argc, char **argv)
{
QApplication app (argc, argv);
VideoWidget v;
v.resize(480, 640);
v.show();
return app.exec();
}
ウィンドウのサイズを変更しながらアスペクト比をロックするにはどうすればよいですか?
この場合、QWidget :: resizeEvent:のオーバーロードを利用できます。
void MyWidget::resizeEvent(QResizeEvent *event)
{
static const float ratioY2X = (float) HEIGHT / (float) WIDTH;
// QResizeEvent type has oldSize() and size()
// and size() has an actual new size for the widget
// so we can just take it and apply the ratio.
// first try to detect the direction of the widget resize
if (event->oldSize().width() != event->size().width())
this->resize(event->size().width(), // apply the correct ratio
event->size().width() * ratioY2X); // to either of width/height
else
this->resize(event->size().height() / ratioY2X, // apply the correct ratio
event->size().height()); // to either of width/height
event->accept(); // we've finished processing resize event here
}
このソリューションにはサイジングのヒントが適用されていないことに注意してください(デフォルト)。
PSif
実際にデバッグを試みた後、オペレーターでこのソリューションを修正しました。ウィジェットの隅をドラッグしてウィジェットのサイズを変更する必要がある場合は、幅が優先されます(ウィジェットを選択する必要がありますが、他にどのように機能しますか?)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加