【发布时间】:2020-07-16 04:33:09
【问题描述】:
我目前正在创建一个 QML 日历,它可以理想地显示来自 Google 日历的事件。
这是我想在 python 中模拟的示例: https://doc.qt.io/qt-5.9/qtquickcontrols-calendar-example.html
现在,一个 python 文件正在从 Google Calendar API 获取日期和事件摘要,并将它们作为 {date: event summary} 的字典(python 代码中的 tenevents 变量)返回。我有一个非常简单的 QML 窗口,显示一个日历和一个矩形。我想单击日历上的某个日期,并让该日期的事件显示在矩形中,并标记有事件的日期。我想我有我需要的大部分数据,我只是不知道如何使用它。我不确定如何在点击时提取日期信息,也不确定如何传递 python 字典并显示我想要的内容——我感谢任何指向有用文档的方向和/或指针!
我在下面包含了我的代码!
getevents() 返回如下内容:
{'2020-07-30T13:00:00-05:00': 'Buy a Single Olive', '2020-07-31T10:00:00-05:00': 'Jarvis', '2020-08-02': 'Peel an Apple', '2020-08-04T02:30:00-05:00': 'Eat Two Crisp Grapes'}
python.py:
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os.path
import os
from PySide2 import QtCore
from PySide2.QtCore import Property, Signal, Slot, QObject, QUrl, QUrlQuery
from PySide2 import QtGui
from PySide2 import QtQml
class CalendarModule(QtCore.QObject):
def __init__(self):
super(CalendarModule, self).__init__()
self.scopes = ['https://www.googleapis.com/auth/calendar']
self.service = self.use_token_pickle_to_get_service()
def use_token_pickle_to_get_service(self):
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
return service
@Slot(result='QVariant')
def getevents(self):
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = self.service.events().list(calendarId='primary', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
tenevents = {}
if not events:
return 'No upcoming events found.'
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
tenevents[start] = event['summary']
return tenevents
def main():
import os
import sys
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
app = QtGui.QGuiApplication(sys.argv)
engine = QtQml.QQmlApplicationEngine()
filename = os.path.join(CURRENT_DIR, "calendar2.qml")
cal = CalendarModule()
engine.rootContext().setContextProperty("Cal", cal)
engine.load(QUrl.fromLocalFile(filename))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
if __name__ == '__main__':
print(CalendarModule().getevents())
main()
calendar2.qml:
import QtQuick 2.3
import QtQuick.Controls.Styles 1.2
import QtQuick.Layouts 1.11
ApplicationWindow {
title: qsTr("Calendar")
width: 700
height: 400
visible: true
RowLayout {
anchors.fill: parent
Rectangle {
id: tasks
Layout.fillWidth: true
Layout.fillHeight: true
height: 400
width: 150
color: "white"
Text {
anchors.horizontalCenter: parent.horizontalCenter
font.bold: true
font.pointSize:14
text: 'To-Do'
}
}
Calendar {
Layout.fillWidth: true
Layout.fillHeight: true
frameVisible: true
style: CalendarStyle {
gridVisible: false
dayDelegate: Rectangle {
gradient: Gradient {
GradientStop {
position: 0.00
color: styleData.selected ? "#111" : (styleData.visibleMonth && styleData.valid ? "#444" : "#666");
}
GradientStop {
position: 1.00
color: styleData.selected ? "#444" : (styleData.visibleMonth && styleData.valid ? "#111" : "#666");
}
GradientStop {
position: 1.00
color: styleData.selected ? "#444" : (styleData.visibleMonth && styleData.valid ? "#111" : "#666");
}
}
Label {
text: styleData.date.getDate()
anchors.centerIn: parent
color: styleData.valid ? "white" : "white"
}
Rectangle {
width: parent.width
height: 1
color: "#555"
anchors.bottom: parent.bottom
}
Rectangle {
width: 1
height: parent.height
color: "#555"
anchors.right: parent.right
}
}
}
}
}
}
【问题讨论】:
标签: python google-api qml pyside2