Jan-12-2021, 04:35 PM
Some suggestions on using Qt.
import sys ### Avoid using from *** import ***. Import the package and use package.thing ### I find this makes it a lot easier to find the Qt specific parts of a program. import PySide2.QtCore as QtCore import PySide2.QtGui as QtGui import PySide2.QtWidgets as QtWidgets from PySide2.QtCore import Qt font = "Arial" stylesheet = 'background-color:black; color:antiquewhite;' ### Give classes names that describe what they are. Give functions and methods ### names that describe what they do class DateTimeDisplay(QtWidgets.QWidget): def __init__(self, *args, **kvargs): super().__init__(*args, **kvargs) ### Avoid set specific sizes and locations for widgets. ### to establish the initial size self.time = QtWidgets.QLabel( '12:00 AM', font=QtGui.QFont(font, 60)) self.date = QtWidgets.QLabel( 'Wednesday, December 31, 2020', font=QtGui.QFont(font, 30)) ### Use layout managers to position widgets ### To size labels, provide representative text to be used layout = QtWidgets.QVBoxLayout(self) layout.addWidget(self.time) layout.addWidget(self.date) self.update() def update(self): """Call to update date and time display""" text = QtCore.QTime.currentTime().toString(Qt.DefaultLocaleShortDate) self.time.setText(text) text = QtCore.QDate.currentDate().toString(Qt.DefaultLocaleLongDate) self.date.setText(text) class Window(QtWidgets.QMainWindow): def __init__(self, *args, **kvargs): super().__init__(*args, **kvargs) ### In most instances the central widget of a main window will be a QWidget or ### a user created class that is subclassed from QWidget. This is an example ### of placing multiple widgets inside the QMainWindow content = QtWidgets.QWidget() datetime_display = DateTimeDisplay() layout = QtWidgets.QVBoxLayout(content) layout.addWidget(QtWidgets.QLabel('This is my cool date time display widget')) layout.addWidget(datetime_display) layout.addWidget(QtWidgets.QLabel('Have a nice day')) self.setCentralWidget(content) ### Avoid embedding usage details in a class. Make the class as generic ### as possible and give the user flexibility on how the class is used. update = QtCore.QTimer(self) update.timeout.connect(datetime_display.update) update.start(1000) App = QtWidgets.QApplication(sys.argv) window = Window() ### Limit using stylesheets. Apply styles to the entire application when ### possible instead of styling individual widgets. window.setStyleSheet(stylesheet) window.show() App.exit(App.exec_())None of these suggestions are rules. I wouldn't even call them guidelines, just suggestions.