Skip to content

Commit

Permalink
add type hints support
Browse files Browse the repository at this point in the history
  • Loading branch information
amaork committed Apr 23, 2021
1 parent 92bce8e commit 80a748d
Show file tree
Hide file tree
Showing 25 changed files with 539 additions and 484 deletions.
1 change: 1 addition & 0 deletions core/datatype.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ def xml2string(xml: XmlElementTree.Element, encode="utf-8") -> Union[str, None]:
print("xml2string error is not xml element object")
return None

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

Expand Down
2 changes: 1 addition & 1 deletion dashboard/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def setHoverColor(cls, color: QColor):
cls.__hoverColor = color

@staticmethod
def color2Tuple(color: QColor):
def color2Tuple(color: QColor) -> Color:
if not isinstance(color, QColor):
return 0, 0, 0

Expand Down
7 changes: 3 additions & 4 deletions demos/button_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ def slotAddButton(self):
if buttonText == "RoundButton":
button = RoundButton(200, text=buttonTextGroup)
elif buttonText == "IconButton":
all = ""
all_ = ""
for name in QImageReader.supportedImageFormats():
all += "*.{} ".format(name)
all_ += "*.{} ".format(name)
files, _ = QFileDialog.getOpenFileNames(self,
"Select icon images",
ImagesPath,
Expand All @@ -62,10 +62,9 @@ def slotAddButton(self):
self.buttonSelect.setDisabled(True)



if __name__ == '__main__':
app = QApplication(sys.argv)
QTextCodec.setCodecForTr(QTextCodec.codecForName("UTF-8"))
widget = DemoWidget()
widget.show()
sys.exit(app.exec_())
sys.exit(app.exec_())
1 change: 0 additions & 1 deletion demos/tabbar_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,3 @@ def slotCreateTabWidget(self):
widget = TabBarDemo()
widget.show()
sys.exit(app.exec_())

2 changes: 1 addition & 1 deletion demos/tarmanager_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def usage():
# Operate
if package_operate:
try:
TarManager.pack(src_path, dest_path, formats, verbose)
TarManager.pack(src_path, dest_path, formats, verbose=verbose)
except TarManagerError as error:
print("Pack error:{}".format(error))

Expand Down
1 change: 1 addition & 0 deletions demos/upgrade_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def server_test(root=UpgradeServer.FILE_SERVER_ROOT):
server = UpgradeServer(file_server_root=root)
server.serve_forever()


if __name__ == '__main__':
# Client mode
if len(sys.argv) == 4:
Expand Down
3 changes: 1 addition & 2 deletions demos/widget_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,6 @@ def showImage(self):
elif self.sender() == self.imageMemButton:
file = showFileImportDialog(parent=self, title="Select image", path=ImagesPath, fmt="All Files (*.jpg)")
if os.path.isfile(file):
data = ""
with open(file, "rb") as fp:
data = fp.read()

Expand All @@ -634,7 +633,7 @@ def showImage(self):
self.imageWidget.setHidden(False)
elif self.sender() == self.imageTextButton:
text, ok = QInputDialog.getText(self, "Please enter text", "Text:",
QLineEdit.Normal, QDir.home().dirName())
QLineEdit.Normal, QDir.home().dirName())
if ok:
self.drawText.emit(text)
self.imageWidget.setHidden(False)
Expand Down
35 changes: 18 additions & 17 deletions gui/binder.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# -*- coding: utf-8 -*-
from PySide.QtCore import QObject
from PySide.QtGui import QSpinBox, QDoubleSpinBox, QLabel, QComboBox
from typing import Optional, Union, Callable, Sequence
from PySide.QtGui import QSpinBox, QDoubleSpinBox, QLabel, QComboBox, QWidget


__all__ = ['SpinBoxBinder', 'ComboBoxBinder']
BinderFactor = Union[int, float, Callable[[Union[int, float]], Union[int, float, str]]]


class SpinBoxBinder(QObject):

def __init__(self, spinbox, parent=None):
def __init__(self, spinbox, parent: Optional[QWidget] = None):
super(SpinBoxBinder, self).__init__(parent)
if not isinstance(spinbox, (QSpinBox, QDoubleSpinBox)):
raise TypeError("spinbox require a {!r} or {!r} not {!r}".format(
Expand All @@ -19,33 +20,33 @@ def __init__(self, spinbox, parent=None):
self.__spinbox.valueChanged.connect(self.eventProcess)

@staticmethod
def __remap(factor, value):
def __remap(factor: BinderFactor, value: Union[int, float]) -> Union[int, float, str]:
if isinstance(factor, (int, float)):
return value * factor
elif hasattr(factor, "__call__"):
return factor(value)
else:
return value

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

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

self.__binding.append((obj, factor))
return True

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

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

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

def eventProcess(self, value):
def eventProcess(self, value: Union[int, float]):
if not isinstance(value, (int, float)):
return

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


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

def bindLabel(self, obj, text):
def bindLabel(self, obj: QLabel, text: Sequence[str]) -> bool:
if not self.__combobox:
return False

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

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

def bindCallback(self, obj, *args):
def bindCallback(self, obj: Callable, *args):
if not hasattr(obj, "__call__"):
print("Bind error, object must be callable object not {!r}".format(obj.__class__.__name__))
print("Bind error, object must be callable object not 'Callable'")
return False

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

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

def eventProcess(self, index):
def eventProcess(self, index: int):
if not isinstance(index, int) or index >= self.__combobox.count():
return

Expand All @@ -151,7 +152,7 @@ def eventProcess(self, index):
receiver.setCurrentIndex(index)
# QLabel
elif isinstance(receiver, QLabel) and isinstance(data[index], str):
receiver.setText(data[index])
receiver.setText(data[index])
# QSpinBox
elif isinstance(receiver, (QSpinBox, QDoubleSpinBox)):
setting = data[index]
Expand Down
50 changes: 30 additions & 20 deletions gui/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,18 @@
|------StateButton
"""
import os.path
from PySide.QtCore import Signal, Qt, QSize
from PySide.QtGui import QPushButton, QKeySequence, QImageReader, QPixmap, QPainter, QFont, QColor, QBrush, QPen
from typing import Optional, Union, Tuple, Sequence
from PySide.QtCore import Signal, Qt, QSize, QRect
from PySide.QtGui import QPushButton, QKeySequence, QImageReader, QPixmap, QPainter, QFont, QColor, QBrush, QPen, \
QWidget, QPaintEvent


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


class BaseButton(QPushButton):
def __init__(self, width=0, height=0, shortCut="", styleSheet="", tips="", parent=None):
def __init__(self, width: int = 0, height: int = 0, shortCut: str = "",
styleSheet: str = "", tips: str = "", parent: Optional[QWidget] = None):
super(BaseButton, self).__init__(parent)
if isinstance(shortCut, str) and len(shortCut):
self.setShortcut(QKeySequence(self.tr(shortCut)))
Expand All @@ -33,10 +36,10 @@ def __init__(self, width=0, height=0, shortCut="", styleSheet="", tips="", paren
self.setToolTip(tips)
self.setStatusTip(tips)

def getState(self):
def getState(self) -> bool:
return self.isChecked() if self.isCheckable() else False

def slotChangeView(self, ck):
def slotChangeView(self, ck: bool):
"""Change button view
:param ck:
Expand All @@ -47,7 +50,8 @@ def slotChangeView(self, ck):


class TextButton(BaseButton):
def __init__(self, width=0, height=0, text=("", ""), shortCut="", styleSheet="", tips="", parent=None):
def __init__(self, width: int = 0, height: int = 0, text: Tuple[str, str] = ("", ""),
shortCut: str = "", styleSheet: str = "", tips: str = "", parent: Optional[QWidget] = None):
super(TextButton, self).__init__(width, height, shortCut, styleSheet, tips, parent)
self.setCheckable(True)
self.toggled.connect(self.slotChangeView)
Expand All @@ -57,7 +61,7 @@ def __init__(self, width=0, height=0, text=("", ""), shortCut="", styleSheet="",
self.text = text
self.setText(self.tr(text[0]))

def slotChangeView(self, ck):
def slotChangeView(self, ck: bool):
"""When button is clicked, change button text
:param ck: Button clicked
Expand All @@ -68,7 +72,7 @@ def slotChangeView(self, ck):


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

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

def paintEvent(self, ev):
def paintEvent(self, ev: QPaintEvent):
pixmap = QPixmap()
painter = QPainter(self)
idx = self.isChecked()
Expand All @@ -110,7 +114,9 @@ def paintEvent(self, ev):


class RectButton(BaseButton):
def __init__(self, width=0, height=0, text=("", ""), shortCut="", color=(Qt.red, Qt.green), tips="", parent=None):
def __init__(self, width: int = 0, height: int = 0, text: Tuple[str, str] = ("", ""), shortCut: str = "",
color: Sequence[Union[Qt.GlobalColor, QColor]] = (Qt.red, Qt.green),
tips: str = "", parent: Optional[QWidget] = None):
super(RectButton, self).__init__(width, height, shortCut, tips=tips, parent=parent)
self.setCheckable(True)

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

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

def setText(self, text):
def setText(self, text: Sequence[str]):
if not isinstance(text, (list, tuple)) or len(text) != 2:
return False

Expand All @@ -139,7 +145,7 @@ def setText(self, text):
self.update()
return True

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

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

def getBrush(self):
def getBrush(self) -> QBrush:
return QBrush(self.drawColor[self.getState()], Qt.SolidPattern)

def paintEvent(self, ev):
def paintEvent(self, ev: QPaintEvent):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
rect = self.rect()
Expand All @@ -168,10 +174,12 @@ def paintEvent(self, ev):


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

def paintEvent(self, ev):
def paintEvent(self, ev: QPaintEvent):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
rect = self.rect()
Expand All @@ -192,14 +200,16 @@ class StateButton(RoundButton):
# Single when state changed
stateChanged = Signal(bool)

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

# Internal state
self.state = False

def getState(self):
def getState(self) -> bool:
return self.state

def turnOn(self):
Expand All @@ -212,7 +222,7 @@ def turnOff(self):
self.stateChanged.emit(False)
self.update()

def slotChangeView(self, ck):
def slotChangeView(self, ck: bool):
if ck:
self.turnOn()
else:
Expand Down
Loading

0 comments on commit 80a748d

Please sign in to comment.