vnpy源碼閱讀學習(4):自己寫一個類似vnpy的界面框架

自己寫一個類似vnpy的界面框架

概述

通過之前3次對vnpy的界面代碼的研究,我們去模仿做一個vn.py的大框架。鞏固一下PyQt5的學習。
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳在這裏插入圖片描述

這部分的代碼相對來說沒有難度和深度,基本上就是把PyQt5的組件進行了使用。主要應用了QVBoxLayout佈局在交易下單的窗體tradingWidget上使用,其他的窗體都大多數用了QTableWidget

關於QTableWidget的教程我找到了一篇:PyQt5高級界面控件之QTableWidget(四)

在vnpy中值得自己學習的是:

  1. vnpy抽象了所有的QTableWidget的對象,因爲交易類的系統用到了大量的列表。所以建立了一個BaseMonitor的對象
  2. 不同的列顯示的方式不太一樣,有的部分可能是直接顯示出來vaule,而有的列表顯示的可能是多空,所以定義了Cell對象。
class BaseCell(QtWidgets.QTableWidgetItem):
    """
    General cell used in tablewidgets.
    """

    def __init__(self, content: Any, data: Any):
        """"""
        super(BaseCell, self).__init__()
        self.setTextAlignment(QtCore.Qt.AlignCenter)
        self.set_content(content, data)

    def set_content(self, content: Any, data: Any):
        """
        Set text content.
        """
        self.setText(str(content))
        self._data = data

    def get_data(self):
        """
        Get data object.
        """
        return self._data
class EnumCell(BaseCell):
    """
    Cell used for showing enum data.
    """

    def __init__(self, content: str, data: Any):
        """"""
        super(EnumCell, self).__init__(content, data)

    def set_content(self, content: Any, data: Any):
        """
        Set text using enum.constant.value.
        """
        if content:
            super(EnumCell, self).set_content(content.value, data)

根據方向不一樣,顯示不同的顏色

class DirectionCell(EnumCell):
    """
    Cell used for showing direction data.
    """

    def __init__(self, content: str, data: Any):
        """"""
        super(DirectionCell, self).__init__(content, data)

    def set_content(self, content: Any, data: Any):
        """
        Cell color is set according to direction.
        """
        super(DirectionCell, self).set_content(content, data)

        if content is Direction.SHORT:
            self.setForeground(COLOR_SHORT)
        else:
            self.setForeground(COLOR_LONG)
class TimeCell(BaseCell):
    """
    Cell used for showing time string from datetime object.
    """

    def __init__(self, content: Any, data: Any):
        """"""
        super(TimeCell, self).__init__(content, data)

    def set_content(self, content: Any, data: Any):
        """
        Time format is 12:12:12.5
        """
        if content is None:
            return

        timestamp = content.strftime("%H:%M:%S")

        millisecond = int(content.microsecond / 1000)
        if millisecond:
            timestamp = f"{timestamp}.{millisecond}"

        self.setText(timestamp)
        self._data = data

界面部分大同小異。接下來研究下MainEngine部分。看看引擎是如何把所有的界面和數據接口穿插起來的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章