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

StackOverflow https://stackoverflow.com/questions/4471456

  •  11-10-2019
  •  | 
  •  

سؤال

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(parent, 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;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top