Qt窗口调整尺寸纵横比1:1

时间:2019-04-14 00:15:57

标签: qt resize window

我想按比例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)不能用..有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您的代码中有一些问题。首先,您应该一次安装事件过滤器,例如在构造函数中。您创建事件过滤器的对象,并在每次触发resizeEvent时安装它,这是错误的。另外,您正在错误的对象(新的QWidget)上安装事件过滤器。因此,删除resizeEvent函数并插入Widget的构造函数中:

FilterObject *filter = new FilterObject();
filter->target=this;
installEventFilter(filter);