Qt窗口调整宽高比1:1

问题描述 投票:0回答:1

我想按比例1:1按比例调整应用窗口大小。我试图在ResizeEvent中更改它,但后来我让窗口闪烁。现在我的代码看起来像这样,但它不起作用。

filterobject.h:

class FilterObject:public QObject{
public:
    QWidget *target = nullptr;//it holds a pointer to target object
    int goalHeight=0;
    FilterObject(QObject *parent=nullptr):QObject(parent){}//uses QObject constructor
    bool eventFilter(QObject *watched, QEvent *event) override;//and overrides eventFilter function
};

widget.h:

namespace Ui {
class Widget;

}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    virtual int heightForWidth ( int w ) const { return w*9/16;}
    //virtual void resizeEvent(QResizeEvent *event) override;
    ~Widget();

private:
    Ui::Widget *ui;
};

widget.cpp:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void QWidget::resizeEvent(QResizeEvent *event){
   FilterObject *filter = new FilterObject();
   QWidget *targetWidget = new QWidget();
   filter->target=targetWidget;
   targetWidget->installEventFilter(filter);
}

bool FilterObject::eventFilter(QObject *watched, QEvent *event) {
    if(watched != target){//checks for correct target object.
        return false;
    }

    if(event->type() != QEvent::Resize){//and correct event
       return false;
    }

    QResizeEvent *resEvent = static_cast<QResizeEvent*>(event);

    goalHeight = 9*resEvent->size().width()/16;
    if(target->height()!=goalHeight){
        target->setFixedHeight(goalHeight);
    }

    return true;
};

也许这段代码可以工作,但我的条件if(event-> type()!= QEvent :: Resize)不起作用..有什么想法吗?

qt resize window
1个回答
0
投票

您的代码中存在一些问题。首先,您应该在构造函数中安装一次事件过滤器。您创建一个事件过滤器的对象,并在每次触发resizeEvent时安装它,这是错误的。你也在错误的对象上安装事件过滤器(一个新的QWidget)。所以删除resizeEvent函数并在Widget的构造函数中插入:

FilterObject *filter = new FilterObject();
filter->target=this;
installEventFilter(filter);
© www.soinside.com 2019 - 2024. All rights reserved.