Skip to content

Commit 80a748d

Browse files
committed
add type hints support
1 parent 92bce8e commit 80a748d

25 files changed

+539
-484
lines changed

core/datatype.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ def xml2string(xml: XmlElementTree.Element, encode="utf-8") -> Union[str, None]:
254254
print("xml2string error is not xml element object")
255255
return None
256256

257+
# Return data is bytes, always need decode
257258
data = XmlElementTree.tostring(xml, encode).strip()
258259
return ComparableXml.string_strip(data.decode())
259260

dashboard/input.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ def setHoverColor(cls, color: QColor):
292292
cls.__hoverColor = color
293293

294294
@staticmethod
295-
def color2Tuple(color: QColor):
295+
def color2Tuple(color: QColor) -> Color:
296296
if not isinstance(color, QColor):
297297
return 0, 0, 0
298298

demos/button_demo.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@ def slotAddButton(self):
4040
if buttonText == "RoundButton":
4141
button = RoundButton(200, text=buttonTextGroup)
4242
elif buttonText == "IconButton":
43-
all = ""
43+
all_ = ""
4444
for name in QImageReader.supportedImageFormats():
45-
all += "*.{} ".format(name)
45+
all_ += "*.{} ".format(name)
4646
files, _ = QFileDialog.getOpenFileNames(self,
4747
"Select icon images",
4848
ImagesPath,
@@ -62,10 +62,9 @@ def slotAddButton(self):
6262
self.buttonSelect.setDisabled(True)
6363

6464

65-
6665
if __name__ == '__main__':
6766
app = QApplication(sys.argv)
6867
QTextCodec.setCodecForTr(QTextCodec.codecForName("UTF-8"))
6968
widget = DemoWidget()
7069
widget.show()
71-
sys.exit(app.exec_())
70+
sys.exit(app.exec_())

demos/tabbar_demo.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,3 @@ def slotCreateTabWidget(self):
5858
widget = TabBarDemo()
5959
widget.show()
6060
sys.exit(app.exec_())
61-

demos/tarmanager_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def usage():
9595
# Operate
9696
if package_operate:
9797
try:
98-
TarManager.pack(src_path, dest_path, formats, verbose)
98+
TarManager.pack(src_path, dest_path, formats, verbose=verbose)
9999
except TarManagerError as error:
100100
print("Pack error:{}".format(error))
101101

demos/upgrade_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ def server_test(root=UpgradeServer.FILE_SERVER_ROOT):
2626
server = UpgradeServer(file_server_root=root)
2727
server.serve_forever()
2828

29+
2930
if __name__ == '__main__':
3031
# Client mode
3132
if len(sys.argv) == 4:

demos/widget_demo.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,6 @@ def showImage(self):
624624
elif self.sender() == self.imageMemButton:
625625
file = showFileImportDialog(parent=self, title="Select image", path=ImagesPath, fmt="All Files (*.jpg)")
626626
if os.path.isfile(file):
627-
data = ""
628627
with open(file, "rb") as fp:
629628
data = fp.read()
630629

@@ -634,7 +633,7 @@ def showImage(self):
634633
self.imageWidget.setHidden(False)
635634
elif self.sender() == self.imageTextButton:
636635
text, ok = QInputDialog.getText(self, "Please enter text", "Text:",
637-
QLineEdit.Normal, QDir.home().dirName())
636+
QLineEdit.Normal, QDir.home().dirName())
638637
if ok:
639638
self.drawText.emit(text)
640639
self.imageWidget.setHidden(False)

gui/binder.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
# -*- coding: utf-8 -*-
22
from PySide.QtCore import QObject
3-
from PySide.QtGui import QSpinBox, QDoubleSpinBox, QLabel, QComboBox
3+
from typing import Optional, Union, Callable, Sequence
4+
from PySide.QtGui import QSpinBox, QDoubleSpinBox, QLabel, QComboBox, QWidget
45

56

67
__all__ = ['SpinBoxBinder', 'ComboBoxBinder']
8+
BinderFactor = Union[int, float, Callable[[Union[int, float]], Union[int, float, str]]]
79

810

911
class SpinBoxBinder(QObject):
10-
11-
def __init__(self, spinbox, parent=None):
12+
def __init__(self, spinbox, parent: Optional[QWidget] = None):
1213
super(SpinBoxBinder, self).__init__(parent)
1314
if not isinstance(spinbox, (QSpinBox, QDoubleSpinBox)):
1415
raise TypeError("spinbox require a {!r} or {!r} not {!r}".format(
@@ -19,33 +20,33 @@ def __init__(self, spinbox, parent=None):
1920
self.__spinbox.valueChanged.connect(self.eventProcess)
2021

2122
@staticmethod
22-
def __remap(factor, value):
23+
def __remap(factor: BinderFactor, value: Union[int, float]) -> Union[int, float, str]:
2324
if isinstance(factor, (int, float)):
2425
return value * factor
2526
elif hasattr(factor, "__call__"):
2627
return factor(value)
2728
else:
2829
return value
2930

30-
def bindLabel(self, obj, factor):
31+
def bindLabel(self, obj: QLabel, factor: BinderFactor) -> bool:
3132
if not isinstance(obj, QLabel):
3233
print("Bind error, object type error:{!r}".format(obj.__class__.__name__))
3334
return False
3435

3536
if not isinstance(factor, (int, float)) and not hasattr(factor, "__call__"):
36-
print("Bind error, factor type error{!r}".format(factor.__class__.__name__))
37+
print("Bind error, factor type error, require: {!r}".format(BinderFactor))
3738
return False
3839

3940
self.__binding.append((obj, factor))
4041
return True
4142

42-
def bindSpinBox(self, obj, factor):
43+
def bindSpinBox(self, obj: Union[QSpinBox, QDoubleSpinBox], factor: BinderFactor) -> bool:
4344
if not isinstance(obj, (QSpinBox, QDoubleSpinBox)):
4445
print("Bind error, object type error:{!r}".format(obj.__class__.__name__))
4546
return False
4647

4748
if not isinstance(factor, (int, float)) and not hasattr(factor, "__call__"):
48-
print("Bind error, factor type error{!r}".format(factor.__class__.__name__))
49+
print("Bind error, factor type error, require: {!r}".format(BinderFactor))
4950
return False
5051

5152
# Set spinbox range and single step
@@ -62,7 +63,7 @@ def bindSpinBox(self, obj, factor):
6263
self.__binding.append((obj, factor))
6364
return True
6465

65-
def eventProcess(self, value):
66+
def eventProcess(self, value: Union[int, float]):
6667
if not isinstance(value, (int, float)):
6768
return
6869

@@ -77,7 +78,7 @@ def eventProcess(self, value):
7778

7879

7980
class ComboBoxBinder(QObject):
80-
def __init__(self, combobox, parent=None):
81+
def __init__(self, combobox: QComboBox, parent: Optional[QWidget] = None):
8182
super(ComboBoxBinder, self).__init__(parent)
8283
if not isinstance(combobox, QComboBox):
8384
raise TypeError("combobox require {!r} not {!r}".format(QComboBox.__name__, combobox.__class__.__name__))
@@ -86,7 +87,7 @@ def __init__(self, combobox, parent=None):
8687
self.__binding = list()
8788
self.__combobox.currentIndexChanged.connect(self.eventProcess)
8889

89-
def bindLabel(self, obj, text):
90+
def bindLabel(self, obj: QLabel, text: Sequence[str]) -> bool:
9091
if not self.__combobox:
9192
return False
9293

@@ -102,7 +103,7 @@ def bindLabel(self, obj, text):
102103
self.eventProcess(self.__combobox.currentIndex())
103104
return True
104105

105-
def bindSpinBox(self, obj, limit):
106+
def bindSpinBox(self, obj: Union[QSpinBox, QDoubleSpinBox], limit: Union[list, tuple]) -> bool:
106107
if not isinstance(obj, (QSpinBox, QDoubleSpinBox)):
107108
print("Bind error, object type error:{!r}".format(obj.__class__.__name__))
108109
return False
@@ -115,15 +116,15 @@ def bindSpinBox(self, obj, limit):
115116
self.eventProcess(self.__combobox.currentIndex())
116117
return True
117118

118-
def bindCallback(self, obj, *args):
119+
def bindCallback(self, obj: Callable, *args):
119120
if not hasattr(obj, "__call__"):
120-
print("Bind error, object must be callable object not {!r}".format(obj.__class__.__name__))
121+
print("Bind error, object must be callable object not 'Callable'")
121122
return False
122123

123124
self.__binding.append((obj, *args))
124125
self.eventProcess(self.__combobox.currentIndex())
125126

126-
def bindComboBox(self, obj, reverse=False):
127+
def bindComboBox(self, obj: QComboBox, reverse: bool = False) -> bool:
127128
if not isinstance(obj, QComboBox):
128129
print("Bind error, object type error:{!r}".format(obj.__class__.__name__))
129130
return False
@@ -136,7 +137,7 @@ def bindComboBox(self, obj, reverse=False):
136137
self.eventProcess(self.__combobox.currentIndex())
137138
return True
138139

139-
def eventProcess(self, index):
140+
def eventProcess(self, index: int):
140141
if not isinstance(index, int) or index >= self.__combobox.count():
141142
return
142143

@@ -151,7 +152,7 @@ def eventProcess(self, index):
151152
receiver.setCurrentIndex(index)
152153
# QLabel
153154
elif isinstance(receiver, QLabel) and isinstance(data[index], str):
154-
receiver.setText(data[index])
155+
receiver.setText(data[index])
155156
# QSpinBox
156157
elif isinstance(receiver, (QSpinBox, QDoubleSpinBox)):
157158
setting = data[index]

gui/button.py

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,18 @@
1111
|------StateButton
1212
"""
1313
import os.path
14-
from PySide.QtCore import Signal, Qt, QSize
15-
from PySide.QtGui import QPushButton, QKeySequence, QImageReader, QPixmap, QPainter, QFont, QColor, QBrush, QPen
14+
from typing import Optional, Union, Tuple, Sequence
15+
from PySide.QtCore import Signal, Qt, QSize, QRect
16+
from PySide.QtGui import QPushButton, QKeySequence, QImageReader, QPixmap, QPainter, QFont, QColor, QBrush, QPen, \
17+
QWidget, QPaintEvent
1618

1719

1820
__all__ = ['TextButton', 'IconButton', 'RectButton', 'RoundButton', 'StateButton']
1921

2022

2123
class BaseButton(QPushButton):
22-
def __init__(self, width=0, height=0, shortCut="", styleSheet="", tips="", parent=None):
24+
def __init__(self, width: int = 0, height: int = 0, shortCut: str = "",
25+
styleSheet: str = "", tips: str = "", parent: Optional[QWidget] = None):
2326
super(BaseButton, self).__init__(parent)
2427
if isinstance(shortCut, str) and len(shortCut):
2528
self.setShortcut(QKeySequence(self.tr(shortCut)))
@@ -33,10 +36,10 @@ def __init__(self, width=0, height=0, shortCut="", styleSheet="", tips="", paren
3336
self.setToolTip(tips)
3437
self.setStatusTip(tips)
3538

36-
def getState(self):
39+
def getState(self) -> bool:
3740
return self.isChecked() if self.isCheckable() else False
3841

39-
def slotChangeView(self, ck):
42+
def slotChangeView(self, ck: bool):
4043
"""Change button view
4144
4245
:param ck:
@@ -47,7 +50,8 @@ def slotChangeView(self, ck):
4750

4851

4952
class TextButton(BaseButton):
50-
def __init__(self, width=0, height=0, text=("", ""), shortCut="", styleSheet="", tips="", parent=None):
53+
def __init__(self, width: int = 0, height: int = 0, text: Tuple[str, str] = ("", ""),
54+
shortCut: str = "", styleSheet: str = "", tips: str = "", parent: Optional[QWidget] = None):
5155
super(TextButton, self).__init__(width, height, shortCut, styleSheet, tips, parent)
5256
self.setCheckable(True)
5357
self.toggled.connect(self.slotChangeView)
@@ -57,7 +61,7 @@ def __init__(self, width=0, height=0, text=("", ""), shortCut="", styleSheet="",
5761
self.text = text
5862
self.setText(self.tr(text[0]))
5963

60-
def slotChangeView(self, ck):
64+
def slotChangeView(self, ck: bool):
6165
"""When button is clicked, change button text
6266
6367
:param ck: Button clicked
@@ -68,7 +72,7 @@ def slotChangeView(self, ck):
6872

6973

7074
class IconButton(BaseButton):
71-
def __init__(self, icons, shortCut="", tips="", parent=None):
75+
def __init__(self, icons: Sequence[str], shortCut: str = "", tips: str = "", parent: Optional[QWidget] = None):
7276
if not isinstance(icons, (list, tuple)):
7377
raise TypeError("icons require a list or tuple type")
7478

@@ -99,7 +103,7 @@ def __init__(self, icons, shortCut="", tips="", parent=None):
99103
else:
100104
print("Icon size mismatched or icon is not a image!")
101105

102-
def paintEvent(self, ev):
106+
def paintEvent(self, ev: QPaintEvent):
103107
pixmap = QPixmap()
104108
painter = QPainter(self)
105109
idx = self.isChecked()
@@ -110,7 +114,9 @@ def paintEvent(self, ev):
110114

111115

112116
class RectButton(BaseButton):
113-
def __init__(self, width=0, height=0, text=("", ""), shortCut="", color=(Qt.red, Qt.green), tips="", parent=None):
117+
def __init__(self, width: int = 0, height: int = 0, text: Tuple[str, str] = ("", ""), shortCut: str = "",
118+
color: Sequence[Union[Qt.GlobalColor, QColor]] = (Qt.red, Qt.green),
119+
tips: str = "", parent: Optional[QWidget] = None):
114120
super(RectButton, self).__init__(width, height, shortCut, tips=tips, parent=parent)
115121
self.setCheckable(True)
116122

@@ -123,12 +129,12 @@ def __init__(self, width=0, height=0, text=("", ""), shortCut="", color=(Qt.red,
123129
self.setColor(color)
124130
self.textLength = max(len(self.text[0]), len(self.text[1]), 1)
125131

126-
def draw(self, painter, rect):
132+
def draw(self, painter: QPainter, rect: QRect):
127133
painter.setPen(self.textColor[self.getState()])
128134
painter.setFont(QFont("Times New Roman", min(rect.width() / self.textLength / 0.618, rect.height() * 0.618)))
129135
painter.drawText(rect, Qt.AlignCenter, self.tr(self.text[self.getState()]))
130136

131-
def setText(self, text):
137+
def setText(self, text: Sequence[str]):
132138
if not isinstance(text, (list, tuple)) or len(text) != 2:
133139
return False
134140

@@ -139,7 +145,7 @@ def setText(self, text):
139145
self.update()
140146
return True
141147

142-
def setColor(self, colors):
148+
def setColor(self, colors: Sequence[Union[Qt.GlobalColor, QColor]]):
143149
if not isinstance(colors, (list, tuple)) or len(colors) != 2:
144150
return False
145151

@@ -150,10 +156,10 @@ def setColor(self, colors):
150156
self.textColor = self.drawColor[1], self.drawColor[0]
151157
self.update()
152158

153-
def getBrush(self):
159+
def getBrush(self) -> QBrush:
154160
return QBrush(self.drawColor[self.getState()], Qt.SolidPattern)
155161

156-
def paintEvent(self, ev):
162+
def paintEvent(self, ev: QPaintEvent):
157163
painter = QPainter(self)
158164
painter.setRenderHint(QPainter.Antialiasing)
159165
rect = self.rect()
@@ -168,10 +174,12 @@ def paintEvent(self, ev):
168174

169175

170176
class RoundButton(RectButton):
171-
def __init__(self, diameter=0, text=("", ""), shortCut="", color=(Qt.red, Qt.green), tips="", parent=None):
177+
def __init__(self, diameter: int = 0, text: Tuple[str, str] = ("", ""),
178+
shortCut: str = "", color: Sequence[Union[Qt.GlobalColor, QColor]] = (Qt.red, Qt.green),
179+
tips: str = "", parent: Optional[QWidget] = None):
172180
super(RoundButton, self).__init__(diameter, diameter, text, shortCut, color, tips, parent)
173181

174-
def paintEvent(self, ev):
182+
def paintEvent(self, ev: QPaintEvent):
175183
painter = QPainter(self)
176184
painter.setRenderHint(QPainter.Antialiasing)
177185
rect = self.rect()
@@ -192,14 +200,16 @@ class StateButton(RoundButton):
192200
# Single when state changed
193201
stateChanged = Signal(bool)
194202

195-
def __init__(self, diameter=0, text=("", ""), shortCut="", color=(Qt.red, Qt.green), tips="", parent=None):
203+
def __init__(self, diameter: int = 0, text: Tuple[str, str] = ("", ""),
204+
shortCut: str = "", color: Sequence[Union[Qt.GlobalColor, QColor]] = (Qt.red, Qt.green),
205+
tips: str = "", parent: Optional[QWidget] = None):
196206
super(StateButton, self).__init__(diameter, text, shortCut, color, tips, parent)
197207
self.setCheckable(False)
198208

199209
# Internal state
200210
self.state = False
201211

202-
def getState(self):
212+
def getState(self) -> bool:
203213
return self.state
204214

205215
def turnOn(self):
@@ -212,7 +222,7 @@ def turnOff(self):
212222
self.stateChanged.emit(False)
213223
self.update()
214224

215-
def slotChangeView(self, ck):
225+
def slotChangeView(self, ck: bool):
216226
if ck:
217227
self.turnOn()
218228
else:

0 commit comments

Comments
 (0)