1.無邊框
Qt Quick 2.0 中 QQuickView代替了1.0中的QDeclarativeView。
無邊框窗口代碼如下:
QQuickView viwer;
//QQuickView繼承自QWindow而不是QWidget
viwer.setFlags(Qt::FramelessWindowHint);
2.窗口透明
setOpacity可設置整個窗口(包括控件)的透明度,而背景透明則應使用setColor
//設置窗口顏色,以下為透明,在viwer.setSource()之前使用 viwer.setColor(QColor(Qt::transparent)); //QWidget用setAttribute(Qt::WA_TranslucentBackground,true)
3.拖拽窗口
拖拽窗口需要將窗口(viewer)設置為qml中的屬性
viwer.rootContext()->setContextProperty("mainwindow",&viwer);
main.cpp如下
/*---main.cpp---*/ #include<QApplication> #include<QQuickView> #include<QColor> #include<QQmlContext> int main(int argc,char* argv[]) { QApplication app(argc,argv); QQuickView viwer; //無邊框,背景透明 viwer.setFlags(Qt::FramelessWindowHint); viwer.setColor(QColor(Qt::transparent)); //加載qml,qml添加到資源文件中可避免qml暴露 viwer.setSource(QUrl("qrc:/qml/main.qml")); viwer.show(); //將viewer設置為main.qml屬性 viwer.rootContext()->setContextProperty("mainwindow",&viwer); return app.exec(); }
此時,main.qml如下即可實現透明,無邊框,可拖拽
/*--main.qml--*/ importQtQuick2.0 Rectangle{ width:300 height:200 //灰色0.9透明度 color:Qt.rgba(0.5,0.5,0.5,0.9) MouseArea{ id: dragRegion anchors.fill: parent 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) } } }
效果如下:
添加關閉按鈕
importQtQuick2.0 Rectangle{ width:300 height:200 //灰色0.9透明度 color:Qt.rgba(0.5,0.5,0.5,0.9) MouseArea{ id: dragRegion anchors.fill: parent 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) } } //要置於MouseArea之后,否則無法響應鼠標點擊 Rectangle{ id:closeBtn height:25 width:25 anchors.right: parent.right anchors.rightMargin:5 anchors.top: parent.top anchors.topMargin:5 color:"#aaff0000" Text{ text:"x" anchors.centerIn: parent } MouseArea{ anchors.fill: parent onClicked: { //Qt.quit()無法關閉窗口 mainwindow.close() } } } }