我有新的PyQt5应用程序。我想在QMainWindow里面添加QQuickWidget并用QML设置他的属性。这就是我的工作:
class mainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(mainWindow,self).__init__()
self.setGeometry(100,100,800,600)
engine = PyQt5.QtQml.QQmlEngine(self)
view = QtQuickWidgets.QQuickWidget(engine,self)
view.setSource(PyQt5.QtCore.QUrl("files/newqml.qml"))
进入QML文件我创建了带状态的矩形,当鼠标悬停在按钮上时应该更改。但是当它徘徊时 - 一切都没有发生。当我点击按钮并单击并离开按钮时状态发生变化。请帮帮我。我怎么能做对的?
完整的QML代码:
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Window 2.2
import QtQuick.Controls.Styles 1.2
Rectangle{
signal buttonPressedSignal
signal buttonReleasedSignal
id: topButton
width:80
height: 40
color: 'white'
border {width: 2; color: '#4CAF50'}
state: 'Normal'
Text {
id: buttonText
anchors.centerIn: parent
text:'Button'
font.pixelSize: 20
font.family: 'Hallo sans'
color: 'black'
}
MouseArea{
anchors.fill: topButton
hoverEnabled: true
onPressed: parent.buttonPressedSignal()
onReleased: parent.buttonReleasedSignal()
onEntered: parent.state='NotNormal'
onExited: parent.state = 'Normal'
}
states:[
State{
name: 'Normal';
PropertyChanges{target:buttonText;color:'black';easing.type:Easing.InOutElastic}
},
State{
name:'NotNormal';
PropertyChanges{target:buttonText;color:'white';easing.type:Easing.InOutElastic}
}
]
transitions:[
Transition{
to: '*'
ColorAnimation{target:buttonText;duration:400}
}
]
}
答案 0 :(得分:0)
问题是您没有正确地将QQuickWidget
添加到QMainWindow
,您必须使用setCentralWidget
或布局来放置它们。此外,qml有一个错误easing.type是PropertyAnimation
的一部分,而不是PropertyChanges
的一部分。
import sys
from PyQt5 import QtWidgets, QtQml, QtQuickWidgets, QtCore
class mainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(mainWindow,self).__init__()
self.setGeometry(100,100,800,600)
engine = QtQml.QQmlEngine(self)
view = QtQuickWidgets.QQuickWidget(engine,self)
view.setSource(QtCore.QUrl("files/newqml.qml"))
self.setCentralWidget(view)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = mainWindow()
w.show()
sys.exit(app.exec_())
<强> .qml 强>
import QtQuick 2.3
Rectangle{
signal buttonPressedSignal
signal buttonReleasedSignal
id: topButton
width:80
height: 40
color: 'white'
border {width: 2; color: '#4CAF50'}
state: 'Normal'
Text {
id: buttonText
anchors.centerIn: parent
text:'Button'
font.pixelSize: 20
font.family: 'Hallo sans'
color: 'black'
}
MouseArea{
anchors.fill: topButton
hoverEnabled: true
onPressed: parent.buttonPressedSignal()
onReleased: parent.buttonReleasedSignal()
onEntered: parent.state='NotNormal'
onExited: parent.state = 'Normal'
}
states:[
State{
name: 'Normal';
PropertyChanges{target:buttonText;color:'black';}
},
State{
name:'NotNormal';
PropertyChanges{target:buttonText;color:'white';}
}
]
transitions:[
Transition{
to: '*'
ColorAnimation{target:buttonText;duration:400}
PropertyAnimation{target:buttonText; easing.type:Easing.InOutElastic;}
}
]
}