我在我的幾個 PyQt5 應用程式中實作了一個顯示當前時間的標簽。這是一個MRE:
import sys
import logging
from PyQt5 import QtWidgets, QtCore, QtGui
__log__ = logging.getLogger()
class App(QtWidgets.QApplication):
def __init__(self, sys_argv):
super(App, self).__init__(sys_argv)
self.main_view = MainView()
self.main_view.show()
class MainView(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setObjectName("MreUi")
self.resize(300, 100)
self.setWindowTitle('MreUi')
self.label = QtWidgets.QLabel()
self.setCentralWidget(self.label)
config_clock(self.label)
self.start_clocks()
def start_clocks(self):
timer = QtCore.QTimer(self)
timer.timeout.connect(self.show_time)
timer.start(1000)
def show_time(self):
current_time = QtCore.QTime.currentTime()
clock_label_time = current_time.toString('hh:mm:ss')
self.label.setText(clock_label_time)
def config_clock(label):
label.setAlignment(QtCore.Qt.AlignCenter)
font = QtGui.QFont('Arial', 24, QtGui.QFont.Bold)
label.setFont(font)
if __name__ == '__main__':
logging.basicConfig()
app = App(sys.argv)
try:
sys.exit(app.exec_())
except Exception as e:
__log__.error('%s', e)
當我在我的幾個 PyQt 應用程式中實作了一個類似的時鐘時,我認為將它實作為一個組件/封裝它會很好。首先,我想通過從任何 QWidget 呼叫 config_clock 函式來做到這一點,并讓該函式完成為指定標簽實作時鐘的所有作業。這將避免在多個應用程式中重復撰寫/呼叫 MainView 的 start_clocks 和 show_time 實體方法。但是當我開始撰寫代碼時...
# from inside my QWidget:
config_clock(self.label)
# this function would live outisde the class, thus reusable by diff Qt apps:
def config_clock(label):
# start the clock
# set default font, etc for label
# instantiate QtCore.QTimer
# # but that's when I realized I've always passed self to QtCore.QTimer and that maybe encapsulating this isn't as trivial as I thought.
我是否應該創建自己的某種 ClockLabel() 物件,該物件通過 QtWidget 的標簽并且也可以是每個可能需要它的 QtWidget 的實體屬性?對我來說,這聞起來有點笨重。但肯定有一種方法可以在 PyQt 中制作“可重用組件”,我只是不知道如何......
如果我將 MainView(QtWidgets.QMainWindow) 作為引數傳遞給我撰寫的 ClockLabel() 類或簽名可能看起來像這樣的 config_clock 函式,我也不確定是否可以正確地將 MainView(QtWidgets.QMainWindow) 稱為“父類” :
def config_clock(label, parent_qtwidget):
# also feels clunky and not sure if parent would be the right term
謝謝
uj5u.com熱心網友回復:
對于 QtWidgets,通過繼承來專門化小部件是很正常的。這是一個如何重新排列代碼以生成可重用小部件的示例:
class ClockLabel(QtWidgets.QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.setAlignment(QtCore.Qt.AlignCenter)
font = QtGui.QFont('Arial', 24, QtGui.QFont.Bold)
self.setFont(font)
self._timer = QtCore.QTimer(self)
self._timer.timeout.connect(self._show_time)
def start(self):
self._timer.start(1000)
def stop(self):
self._timer.stop()
def _show_time(self):
current_time = QtCore.QTime.currentTime()
clock_label_time = current_time.toString('hh:mm:ss')
self.setText(clock_label_time)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414853.html
標籤:
