开发者

Displaying QML file with custom QT code (implementing resize/move functionality)

开发者 https://www.devze.com 2023-01-31 15:57 出处:网络
What is the best way of displaying a QML file with custom QT C++ code ? I tried creating a QWidget without a window border like

What is the best way of displaying a QML file with custom QT C++ code ? I tried creating a QWidget without a window border like

main.cpp

#include "stdafx.h"
#include "myqmlapp.h"
#include <QtGui/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyQMLApp w(NULL, Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
    w.show();
    return a.exec();
}

myqmlapp.cpp

MyQMLApp::MyQMLApp(QWidget *parent, Qt::WFlags flags)
    : QWidget(pare开发者_运维问答nt, flags), qmlView(this)
{
    QApplication::instance()->connect(qmlView.engine(), SIGNAL(quit()), SLOT(quit()));

    qmlView.setSource(QUrl("qrc:test1.qml"));
    qmlView.show();

    ui.setupUi(this);
}

And my application window is this widget. So the only thing visible is the output of my QML file. But this has some problems. Since I don't have a window border I can't do resize/move.

How can I implement a window border with QML ?


You may write them manually. For example, catch mouse events, determine click region, and work with it as if it was window header or border. All coordinates where y coordinate is lower than 30 may be "header" region, all within 5 pixels near widget edge may be "border" region etc. After that reimplement mouse catching events, such as mouseMoveEvent,mouseClickEvent etc to do what you need basing on current mouse region.

Piece of code which moving the window.

typedef enum WidgetRegion {HEADER_REGION, BORDER_REGION, ... } WidgetRegion;

windowlessWidget::windowlessWidget(QWidget* parent):QWidget(parent)
{
...
setMouseTracking (true);

}

WidgetRegion windowlessWidget::calculateWindowRegion(QPoint mousePos)
{
  ...
  return region;
}
void windowlessWidget::mousePressEvent(QMouseEvent* event)
{
    if(calculateWindowRegion(event->pos())==HEADER_REGION)
    if(event->button() == Qt::LeftButton)
    {
        mMoving = true;
        mLastMousePosition = event->globalPos();
    }
}

void windowlessWidget::mouseMoveEvent(QMouseEvent* event)
{
    if(calculateWindowRegion(event->pos())==HEADER_REGION)
     if( event->buttons().testFlag(Qt::LeftButton) && mMoving)
     {                                  //offset
         window()->move(window()->pos() + (event->globalPos() - mLastMousePosition));
         mLastMousePosition = event->globalPos();
     }
}

void windowlessWidget::mouseReleaseEvent(QMouseEvent* event)
{
    if(calculateWindowRegion(event->pos())==HEADER_REGION)
    if(event->button() == Qt::LeftButton)
    {
        mMoving = false;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消