0

I have a problem. I want to get a selected date in the format 2021-12-12 from the PyQt calendar. I can print out the variable date (commented) in the get_date function but I could not access this variable from outside. So I created the time variable and wanted to overwrite the variable through the function, but when I try to print out time after the code I get "None".

Do you have any recommendations?

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QDate, QTime, QDateTime, Qt
import sys

app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.setWindowTitle("Datumsauswahl")
cal = QtWidgets.QCalendarWidget(gridVisible=True)
lay = QtWidgets.QVBoxLayout(window)
lay.addWidget(cal)
time = datetime.datetime.now()
@QtCore.pyqtSlot(QtCore.QDate)
def get_date(date): # <--- date parameter
    date = date.toString(Qt.ISODate)
    #print(date)
    time = date
#time = get_date(date)    
time = cal.clicked.connect(get_date)
window.show()
print(time)
sys.exit(app.exec())
print(time)
  • First of all, a `signal.connect()` returns `None`, so your first `time = ...` is wrong. Then, when you try to print `time` the first time, it's still `None`, because at that time the window has just been shown, and the `time` variable is not set yet (it would be set only as soon as a date is clicked, but that's just a local variable, it's valid only in the scope of `get_date()`). Finally, Qt slots only work inside a QObject class, so it's useless for a normal function. – musicamante Dec 13 '21 at 19:22
  • Thank you very much for your help. But how could I get the variable for public? – Florian Goertler Dec 14 '21 at 07:24
  • Read the question marked as duplicate, but remember that globals should be ***always*** used with care (and are generally avoided, as their usage is usually caused by inexperience and bad coding): most of the times, if you're using globals, you're doing it wrong. Instances and attributes should always be preferred. – musicamante Dec 14 '21 at 14:46

0 Answers0