简体   繁体   English

如何将 sql 数据输出到 QCalendarWidget

[英]How to Output sql data onto a QCalendarWidget

I want to be able to highlight a day from my SQL Database on my calendar widget just like how the current day is highlighted when you start the program, in my example it is a red highlight.我希望能够在我的日历小部件上突出显示 SQL 数据库中的一天,就像启动程序时突出显示当前日期一样,在我的示例中,它是红色突出显示。

What i want to happen is when the user presses on the date that is highlighted the text that is alongside the date in the databse is displayed on the label below the calendar.我想要发生的是当用户按下突出显示的日期时,数据库中日期旁边的文本显示在日历下方的标签上。

This is my page i made using QT Designer:这是我使用 QT Designer 创建的页面:

PYQT Page PYQT页面

This is the database that has all the data:这是包含所有数据的数据库:

SQL Database SQL 数据库

And this is the code that creates the QT Page:这是创建 QT 页面的代码:

    # -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Calendar.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
import datetime
import PyQt5
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtGui import (QColor, QFont, QTextCharFormat, QTextLength,
        QTextTableFormat)
from PyQt5.QtWidgets import (QApplication, QComboBox, QDateTimeEdit,
        QHBoxLayout, QLabel, QMainWindow, QSpinBox, QTextBrowser, QVBoxLayout,
        QWidget)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1200, 900)
        MainWindow.setMinimumSize(QtCore.QSize(0, 0))
        MainWindow.setMaximumSize(QtCore.QSize(1200, 900))
        MainWindow.setStyleSheet("background-color: rgb(200, 200, 200);")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Header = QtWidgets.QTextEdit(self.centralwidget)
        self.Header.setEnabled(False)
        self.Header.setGeometry(QtCore.QRect(-10, 0, 1300, 110))
        self.Header.setMinimumSize(QtCore.QSize(1300, 110))
        self.Header.setMaximumSize(QtCore.QSize(1300, 110))
        self.Header.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-color: rgb(255, 255, 255);\n"
"border-width : 1.2px;\n"
"border-style:inset;")
        self.Header.setObjectName("Header")
        self.LECTURP = QtWidgets.QLabel(self.centralwidget)
        self.LECTURP.setGeometry(QtCore.QRect(512, 2, 180, 61))
        self.LECTURP.setStyleSheet("color: rgb(0, 176, 240);\n"
"font: 8pt \"MS Shell Dlg 2\";\n"
"text-decoration: underline;\n"
"background-color: rgb(255, 255, 255);\n"
"font: 28pt \"Calbri\";\n"
"text-decoration: underline;")
        self.LECTURP.setObjectName("LECTURP")
        self.LecturpBanner = QtWidgets.QLabel(self.centralwidget)
        self.LecturpBanner.setGeometry(QtCore.QRect(320, 60, 561, 31))
        self.LecturpBanner.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 176, 240);\n"
"font: 14pt \"Calibri\";")
        self.LecturpBanner.setObjectName("LecturpBanner")
        self.calendarWidget = QtWidgets.QCalendarWidget(self.centralwidget)
        self.calendarWidget.setGeometry(QtCore.QRect(30, 110, 1141, 661))
        self.calendarWidget.setStyleSheet("alternate-background-color: rgb(255, 255, 255);\n"
"font: 75 16pt \"MS Shell Dlg 2\";\n"
"background-color: rgb(200, 200, 200);\n"
"selection-background-color: rgb(255, 0, 0);")
        self.calendarWidget.setObjectName("calendarWidget")
        self.DateInfoOutput = QtWidgets.QLabel(self.centralwidget)
        self.DateInfoOutput.setGeometry(QtCore.QRect(30, 778, 1141, 97))
        self.DateInfoOutput.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-color: rgb(0, 0, 0);\n"
"font: 16pt \"Calibri\";\n"
"border-width : 1.2px;\n"
"border-style:inset;")
        self.DateInfoOutput.setText("")
        self.DateInfoOutput.setObjectName("DateInfoOutput")
        self.WeekNumber = QtWidgets.QLabel(self.centralwidget)
        self.WeekNumber.setGeometry(QtCore.QRect(56, 168, 113, 49))
        self.WeekNumber.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"font: 16pt \"MS Shell Dlg 2\";")
        self.WeekNumber.setObjectName("WeekNumber")
        self.calendarWidget.raise_()
        self.Header.raise_()
        self.LECTURP.raise_()
        self.LecturpBanner.raise_()
        self.DateInfoOutput.raise_()
        self.WeekNumber.raise_()
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.editor = QTextBrowser()



    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.LECTURP.setText(_translate("MainWindow", "LECTURP"))
        self.LecturpBanner.setText(_translate("MainWindow", "Lecture, Exam, Coursework, Timetable, Uploader and Reminder Program."))
        self.WeekNumber.setText(_translate("MainWindow", "Week No."))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

In my code i attempted to do this using this code.在我的代码中,我尝试使用此代码执行此操作。 This part of the code gives an error where the date = Qdate(All_Dates, 3) part gives an error.这部分代码给出了一个错误,其中 date = Qdate(All_Dates, 3) 部分给出了一个错误。

The error that is created is this: arguments did not match any overloaded call: QDate(): too many arguments QDate(int, int, int): argument 1 has unexpected type 'str' QDate(int, int, int, QCalendar): argument 1 has unexpected type 'str' The code below is just to create the QT page:创建的错误是这样的:参数与任何重载调用不匹配:QDate():参数太多QDate(int,int,int):参数1具有意外类型'str'QDate(int,int,int,QCalendar) : 参数 1 有意外类型 'str' 下面的代码只是为了创建 QT 页面:

connection = sqlite3.connect("Calendardatabase.db") 
        # This is the code for the database cursor 
        crsr = connection.cursor() 
        Count = 1
        crsr.execute('SELECT Day FROM Calendar WHERE Number = ?', (Count,))
        RawDay = crsr.fetchone()
        Day = str(RawDay)
        Day = Day.replace('(', '')
        Day = Day.replace(')', '')
        Day = Day.replace(',', '')
        Day = int(Day)

        crsr.execute('SELECT Month FROM Calendar WHERE Number = ?', (Count,))
        RawMonth = crsr.fetchone()
        Month = str(RawMonth)
        Month = Month.replace('(', '')
        Month = Month.replace(')', '')
        Month = Month.replace(',', '')
        Month = int(Month)

        crsr.execute('SELECT Year FROM Calendar WHERE Number = ?', (Count,))
        RawYear = crsr.fetchone()
        Year = str(RawDay)
        Year = Year.replace('(', '')
        Year = Year.replace(')', '')
        Year = Year.replace(',', '')
        Year = int(Year)        


        Current_Day = datetime.date.today().strftime("%A,")
        Current_Date = datetime.date.today().strftime("%d")
        Current_Month = datetime.date.today().strftime("%B")


        Combined_Date = ("It is a " + Current_Day + " It is the " + Current_Date + " of " + Current_Month)

        Combined_Date = str(Combined_Date)

        self.DateInfoOutput.setText(Combined_Date)

        cursor = self.editor.textCursor()

        self.selectedDate = QDate.currentDate()


        All_Dates = (Day, Month, Year)
        All_Dates = str(All_Dates)



        date = QDate(All_Dates, 3)

        format = cursor.charFormat()
        format.setFontPointSize(self.fontSize)

        boldFormat = QTextCharFormat(format)
        boldFormat.setFontWeight(QFont.Bold)

        highlightedFormat = QTextCharFormat(boldFormat)
        highlightedFormat.setBackground(Qt.yellow)


        cell = table.cellAt(0, weekDay-1)
        cellCursor = cell.firstCursorPosition()
        cellCursor.insertText(QDate.longDayName(weekDay), boldFormat)

You need to connect to the clicked(date) signal.您需要连接到clicked(date)信号。

    def dateClicked(self, clickedDate):
        connection = sqlite3.connect("Calendardatabase.db") 
        crsr = connection.cursor() 
        crsr.execute(
            'SELECT Text FROM Calendar WHERE Day = ? AND Month = ? AND YEAR = ?', 
            (clickedDate.day(), clickedDate.month(), clickedDate.year()))
        result = crsr.fetchone()
        if result:
            self.dateInfoOutput.setText(result[0])
        else:
            self.dateInfoOutput.setText('')

Besides that:除此之外:

  1. Never, NEVER edit the files created with pyuic, use them as modules instead.永远不要编辑用 pyuic 创建的文件,而是将它们用作模块。 Read more on using Designer .阅读有关使用 Designer 的更多信息。
  2. Avoid using uppercase names for variables and attributes.避免对变量和属性使用大写名称。
  3. Avoid fixed position and size of widgets unless it is really necessary (which usually isn't);除非真的有必要(通常​​不是),否则避免固定小部件的位置和大小; prefer layouts instead, they are easily accessible in the widget box of Designer or can be set on existing widget from their context menu.更喜欢布局,它们可以在 Designer 的小部件框中轻松访问,也可以从上下文菜单中对现有小部件进行设置。
  4. When providing example code in questions, always ensure that they are both minimal and reproducible .在问题中提供示例代码时,请始终确保它们都是最小的且可重现的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM