qml滑鼠拖動 qml實現視窗拖動

2021-10-17 06:13:03 字數 1654 閱讀 6281

在去掉視窗標題欄後視窗會失去滑鼠拖動效果,所以需要自己新增拖動效果。

實現**:

id: mainwindow

visible: true

width: 900

height: 600

title: qstr("hello world")

flags: qt.window | qt.framelesswindowhint //去標題欄

property int mainwindowx //用來儲存主視窗x座標

property int mainwindowy //儲存視窗y座標

property int xmouse //儲存滑鼠x座標

property int ymouse //儲存滑鼠y座標

mousearea { //為視窗新增滑鼠事件

anchors.fill: parent

acceptedbuttons: qt.leftbutton //只處理滑鼠左鍵

onpressed: { //接收滑鼠按下事件

xmouse = mou***

ymouse = mousey

mainwindowx = mainwindow.x

mainwindowy = mainwindow.y

onpositionchanged: { //滑鼠按下後改變位置

mainwindow.x = mainwindowx + (mou*** - xmouse)

mainwindow.y = mainwindowx + (mousey - ymouse)

解析:在滑鼠被按下後將當前的視窗座標和滑鼠當前座標儲存,帶滑鼠在按下左鍵後進行移動時,首先用mou*** – xmouse和mousey – ymouse計算出滑鼠在x軸和y軸所移動的距離,然後將滑鼠移動的距離與主視窗的x,y座標相加得出視窗的變換座標,然後設定主視窗的座標令其改變位置。

使用上述方法雖然能實現視窗的拖動,但是效果卻不佳,在用滑鼠進行拖動的時候視窗的移動會出現延遲和卡頓的現象,所以建議使用下面這種方法:

id: mainwindow

visible: true

width: 900

height: 600

title: qstr("hello world")

flags: qt.window | qt.framelesswindowhint //去標題欄

mousearea { //為視窗新增滑鼠事件

anchors.fill: parent

acceptedbuttons: qt.leftbutton //只處理滑鼠左鍵

property point clickpos: "0,0"

onpressed: { //接收滑鼠按下事件

clickpos = qt.point(mouse.x,mouse.y)

onpositionchanged: { //滑鼠按下後改變位置

//滑鼠偏移量

var delta = qt.point(mouse.x-clickpos.x, mouse.y-clickpos.y)

//如果mainwindow繼承自qwidget,用setpos

mainwindow.setx(mainwindow.x+delta.x)

mainwindow.sety(mainwindow.y+delta.y)

QML如何實現視窗縮放隱藏

上面實現了視窗以矩形的方式進行縮放隱藏和顯示。該功能主要使用了qml動畫中的numberanimation來實現,下面簡單介紹一下numberanimation。numberanimation顧名思義就是數字動畫,可以改變型別為數值的屬性,從而產生一系列的動畫,例如,width,height,rad...

QML設定視窗背景

剛開始接觸qml 先上圖了 上 import qtquick 2.4 import qtquick.controls 1.3 import qtquick.window 2.2 import qtquick.dialogs 1.2 title qstr hello world width 640 h...

qml 多級視窗visible現象

多級視窗可以通過動態元件進行實現,也可以通過loader載入。然而,在此要注意視窗顯示 隱藏的順序 1 當視窗層級為主視窗 子視窗a 子視窗b 這種模式,a是b的父視窗,那麼在進行顯示時,必須先顯示a,在顯示b,同時,在隱藏時,要先隱藏b,在隱藏a,如果先隱藏了a,再隱藏b,就會出現主視窗自動最小化...