Exemplo n.º 1
0
    def createSplineChart(self):
        chart = QChart()
        chart.setTitle("Spline chart")

        for i, data_list in enumerate(self.m_dataTable):
            series = QSplineSeries(chart)
            for value, _ in data_list:
                series.append(value)

            series.setName("Series " + str(i))
            chart.addSeries(series)

        chart.createDefaultAxes()

        return chart
Exemplo n.º 2
0
    def createSplineChart(self):
        chart = QChart()
        chart.setTitle("Spline chart")

        for i, data_list in enumerate(self.m_dataTable):
            series = QSplineSeries(chart)
            for value, _ in data_list:
                series.append(value)

            series.setName("Series " + str(i))
            chart.addSeries(series)

        chart.createDefaultAxes()

        return chart
Exemplo n.º 3
0
class DynamicSpline(QChart):
    def __init__(self):
        super().__init__()
        self.m_step = 0
        self.m_x = 2
        self.m_y = 1
        # Инициализировать изображение
        self.series = QSplineSeries(self)
        red_pen = QPen(Qt.red)
        red_pen.setWidth(2)
        self.series.setPen(red_pen)
        self.axisX = QValueAxis()
        self.axisY = QValueAxis()
        self.series.append(self.m_x, self.m_y)

        self.addSeries(self.series)
        self.addAxis(self.axisX, Qt.AlignBottom)
        self.addAxis(self.axisY, Qt.AlignLeft)
        self.series.attachAxis(self.axisX)
        self.series.attachAxis(self.axisY)
        self.axisX.setTickCount(5)
        self.axisX.setRange(0, 10)
        self.axisY.setRange(0, 100)

        self.timer = QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.handleTimeout)
        self.timer.start()


    def handleTimeout(self):
        x = self.plotArea().width() / self.axisX.tickCount()
        y = (self.axisX.max() - self.axisX.min()) / self.axisX.tickCount()
        self.m_x += y

        # В PyQt 5.11.3 и выше, QRandomGenerator.global() был переименован в global_()
        try:
            self.m_y=db_wrk()
        except :
            self.m_y = QRandomGenerator.global_().bounded(50)
        self.series.append(self.m_x, self.m_y)
        self.scroll(x, 0)
        if self.m_x >= 10:
            self.timer.stop()

    def db_wrk():

        return m_y
Exemplo n.º 4
0
class CpuLineChart(QChart):

    def __init__(self, *args, **kwargs):
        super(CpuLineChart, self).__init__(*args, **kwargs)
        self.m_count = 10
        # 隐藏图例
        self.legend().hide()
        self.m_series = QSplineSeries(self)
        # 设置画笔
        self.m_series.setPen(QPen(QColor('#3B8CFF'), 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        self.addSeries(self.m_series)
        # x轴
        self.m_axisX = QDateTimeAxis(self)
        self.m_axisX.setTickCount(self.m_count + 1)  # 设置刻度数量
        self.m_axisX.setFormat('hh:mm:ss')  # 设置时间显示格式
        now = QDateTime.currentDateTime()  # 前10秒到现在
        self.m_axisX.setRange(now.addSecs(-self.m_count), now)
        self.addAxis(self.m_axisX, Qt.AlignBottom)
        self.m_series.attachAxis(self.m_axisX)
        # y轴
        self.m_axisY = QValueAxis(self)
        self.m_axisY.setLabelFormat('%d')  # 设置文本格式
        self.m_axisY.setMinorTickCount(4)  # 设置小刻度线的数目
        self.m_axisY.setTickCount(self.m_count + 1)
        self.m_axisY.setRange(0, 100)
        self.addAxis(self.m_axisY, Qt.AlignLeft)
        self.m_series.attachAxis(self.m_axisY)

        # 填充11个初始点,注意x轴 需要转为秒的时间戳
        self.m_series.append(
            [QPointF(now.addSecs(-i).toMSecsSinceEpoch(), 0) for i in range(self.m_count, -1, -1)])

        # 定时器获取数据
        self.m_timer = QTimer()
        self.m_timer.timeout.connect(self.update_data)
        self.m_timer.start(1000)

    def update_data(self):
        value = cpu_percent()
        now = QDateTime.currentDateTime()
        self.m_axisX.setRange(now.addSecs(-self.m_count), now)  # 重新调整x轴的时间范围
        # 获取原来的所有点,去掉第一个并追加新的一个
        points = self.m_series.pointsVector()
        points.pop(0)
        points.append(QPointF(now.toMSecsSinceEpoch(), value))
        # 替换法速度更快
        self.m_series.replace(points)
Exemplo n.º 5
0
    def __init__(self, parent=None):
        super().__init__(QGraphicsScene(), parent)
        self.m_tooltip = None
        self.m_callouts = []

        self.setDragMode(QGraphicsView.NoDrag)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # chart
        self.m_chart = QChart()
        self.m_chart.setMinimumSize(640, 480)
        self.m_chart.setTitle(
            "Hover the line to show callout. Click the line to make it stay"
        )
        self.m_chart.legend().hide()
        series = QLineSeries()
        series.append(1, 3)
        series.append(4, 5)
        series.append(5, 4.5)
        series.append(7, 1)
        series.append(11, 2)
        self.m_chart.addSeries(series)

        series2 = QSplineSeries()
        series2.append(1.6, 1.4)
        series2.append(2.4, 3.5)
        series2.append(3.7, 2.5)
        series2.append(7, 4)
        series2.append(10, 2)
        self.m_chart.addSeries(series2)

        self.m_chart.createDefaultAxes()
        self.m_chart.setAcceptHoverEvents(True)

        self.setRenderHint(QPainter.Antialiasing)
        self.scene().addItem(self.m_chart)

        self.m_coordX = QGraphicsSimpleTextItem(self.m_chart)
        self.m_coordX.setPos(
            self.m_chart.size().width() / 2 - 50, self.m_chart.size().height()
        )
        self.m_coordX.setText("X: ")
        self.m_coordY = QGraphicsSimpleTextItem(self.m_chart)
        self.m_coordY.setPos(
            self.m_chart.size().width() / 2 + 50, self.m_chart.size().height()
        )
        self.m_coordY.setText("Y: ")

        series.clicked.connect(self.keepCallout)
        series.hovered.connect(self.tooltip)

        series2.clicked.connect(self.keepCallout)
        series2.hovered.connect(self.tooltip)

        self.setMouseTracking(True)
Exemplo n.º 6
0
class Chart(QChart):

    def __init__(self):
        super(QChart, self).__init__()

        self.m_timer = QTimer()
        self.m_series = None
        self.m_titles = []
        self.m_axis = QValueAxis()
        self.m_step = None
        self.m_x = 5
        self.m_y = 1

        random.seed(QTime.currentTime().msec())

        self.m_timer.timeout.connect(self.handleTimeout)
        self.m_timer.setInterval(1000)

        self.m_series = QSplineSeries(self)
        green = QPen(Qt.green)
        green.setWidth(3)
        self.m_series.setPen(green)
        self.m_series.append(self.m_x, self.m_y)

        self.addSeries(self.m_series)
        self.createDefaultAxes()
        self.setAxisX(self.m_axis, self.m_series)
        self.m_axis.setTickCount(5)
        self.axisX().setRange(0, 10)
        self.axisY().setRange(-5, 10)

        self.m_timer.start()


    @pyqtSlot()
    def handleTimeout(self):
        x = self.plotArea().width() / self.m_axis.tickCount()
        y = (self.m_axis.max() - self.m_axis.min()) / self.m_axis.tickCount()
        self.m_x += y
        self.m_y = random.randint(0, 5) - 2.5
        self.m_series.append(self.m_x, self.m_y)
        self.scroll(x, 0)
        if self.m_x is 100:
            self.m_timer.stop()
Exemplo n.º 7
0
class DynamicSpline(QChart):
    def __init__(self):
        super().__init__()
        self.m_step = 0
        self.m_x = 5
        self.m_y = 1
        # 初始化图像
        self.series = QSplineSeries(self)
        green_pen = QPen(Qt.red)
        green_pen.setWidth(3)
        self.series.setPen(green_pen)
        self.axisX = QValueAxis()
        self.axisY = QValueAxis()
        self.series.append(self.m_x, self.m_y)

        self.addSeries(self.series)
        self.addAxis(self.axisX, Qt.AlignBottom)
        self.addAxis(self.axisY, Qt.AlignLeft)
        self.series.attachAxis(self.axisX)
        self.series.attachAxis(self.axisY)
        self.axisX.setTickCount(5)
        self.axisX.setRange(0, 10)
        self.axisY.setRange(-5, 10)

        self.timer = QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.handleTimeout)
        self.timer.start()

    def handleTimeout(self):
        x = self.plotArea().width() / self.axisX.tickCount()
        y = (self.axisX.max() - self.axisX.min()) / self.axisX.tickCount()
        self.m_x += y
        # 在PyQt5.11.3及以上版本中,QRandomGenerator.global()被重命名为global_()
        self.m_y = QRandomGenerator.global_().bounded(5) - 2.5
        self.series.append(self.m_x, self.m_y)
        self.scroll(x, 0)
        if self.m_x >= 100:
            self.timer.stop()
Exemplo n.º 8
0
class BalanceHistoryChartView(QChartView):
    """
    Chart that displays the balance between several dates
    from an account, token or whole portfolio
    """

    def __init__(self,  *args,  **kwargs):
        super().__init__(*args, **kwargs)

        self.chart = QChart()
        self.FIAT_CURRENCY = confighandler.get_fiat_currency()

    def setupChartWithData(self, selectiontype, name=None):
        """
        Chart gets updated displaying new data.
        The data gets extracted from cbalancehistory, according 
        to the selection

        Parameters:
            - selectiontype : in ('account','token','all')
            - name: str, corresponds to account/token on cbalancehistory

        """
        self.chart = QChart()

        self.chart.setTheme(QChart.ChartThemeDark)
        self.chart.setAnimationOptions(QChart.SeriesAnimations)
        self.chart.setBackgroundBrush(QBrush(QColor('#19232d')))
#         self.chart.setTitle("")
#         self.chart.setTitleBrush(QBrush(QColor('white')))

        # Data
        # Get data
        if selectiontype == 'token':
            assert(name is not None)
            data = chistoricalbalances.get_balances_with_token_tuple(name)
        elif selectiontype == 'account':
            assert(name is not None)
            data = chistoricalbalances.get_balances_with_account_tuple(name)
        elif selectiontype == 'all':
            data = chistoricalbalances.get_balances_by_day_tuple()
        # Separate balance_btc from balance_fiat
        dates, balances_btc, balances_fiat = [], [], []
        for date in data:
            dates.append(int(date))
            balances_btc.append(data[date][0])
            balances_fiat.append(data[date][1])

        # Series
        self.btcseries = QSplineSeries()
        self.fiatseries = QSplineSeries()
        for date, balance_btc, balance_fiat in zip(dates, balances_btc, balances_fiat):
            date = datetime.fromtimestamp(date)
            date = datetime(date.year, date.month, date.day)
            dateQ = QDateTime(date).toMSecsSinceEpoch()
            self.btcseries.append(dateQ, balance_btc)
            self.fiatseries.append(dateQ, balance_fiat)

        # Append current point
        currentdate = QDateTime(datetime.today()).toMSecsSinceEpoch()
        if selectiontype == "all":
            # Append current balances
            self.btcseries.append(currentdate,
                                  cbalances.get_total_balance_all_accounts())
            self.fiatseries.append(currentdate,
                                   cbalances.get_total_balance_all_accounts_fiat())
        elif name != '':
            if selectiontype == "account":
                # Append current balances
                self.btcseries.append(
                    currentdate, cbalances.get_total_account_balance(name))
                self.fiatseries.append(
                    currentdate, cbalances.get_total_account_balance_fiat(name))
            elif selectiontype == "token":
                pass

        # Axis X (Dates)
        self.x_axis = QDateTimeAxis()
        self.x_axis.setTickCount(11)
        self.x_axis.setLabelsAngle(70)
        self.x_axis.setFormat("dd-MM-yy")
        self.x_axis.setTitleText(self.tr('Date'))

        # Axis Y (Balances)
        # BTC
        self.y_axis_btc = QValueAxis()
        if len(balances_btc) > 0:
            self.y_axis_btc.setMax(max(balances_btc)*1.1)
            self.y_axis_btc.setMin(min(balances_btc)*0.9)
        # Fiat
        self.y_axis_fiat = QValueAxis()
        if len(balances_fiat) > 0:
            self.y_axis_fiat.setMax(max(balances_fiat)*1.1)
            self.y_axis_fiat.setMin(min(balances_fiat)*0.9)

        self.chart.addAxis(self.y_axis_btc, Qt.AlignLeft)
        self.chart.addAxis(self.y_axis_fiat, Qt.AlignRight)
        self.chart.addAxis(self.x_axis, Qt.AlignBottom)

        # Add series to chart
        # BTC
        self.btcseries.setName("BTC")
        self.chart.addSeries(self.btcseries)
        self.btcseries.attachAxis(self.x_axis)
        self.btcseries.attachAxis(self.y_axis_btc)
        # Fiat
        self.fiatseries.setName(self.FIAT_CURRENCY.upper())
        self.chart.addSeries(self.fiatseries)
        self.fiatseries.attachAxis(self.x_axis)
        self.fiatseries.attachAxis(self.y_axis_fiat)

        self.setChart(self.chart)
        self.setRenderHint(QPainter.Antialiasing)
        self.setStyleSheet("border: 0px")
Exemplo n.º 9
0
class ChartView(QChartView, QChart):
    def __init__(self, *args, **kwargs):
        super(ChartView, self).__init__(*args, **kwargs)
        self.resize(800, 600)
        self.setRenderHint(QPainter.Antialiasing)  # 抗锯齿
        self.chart_init()
        self.timer_init()

    def timer_init(self):
        #使用QTimer,2秒触发一次,更新数据
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.drawLine)
        self.timer.start(200)

    def chart_init(self):
        self.chart = QChart()
        self.series = QSplineSeries()
        #设置曲线名称
        self.series.setName("实时数据")
        #把曲线添加到QChart的实例中
        self.chart.addSeries(self.series)
        #声明并初始化X轴,Y轴
        self.dtaxisX = QDateTimeAxis()
        self.vlaxisY = QValueAxis()
        #设置坐标轴显示范围
        self.dtaxisX.setMin(QDateTime.currentDateTime().addSecs(-300 * 1))
        self.dtaxisX.setMax(QDateTime.currentDateTime().addSecs(0))
        self.vlaxisY.setMin(0)
        self.vlaxisY.setMax(1500)
        #设置X轴时间样式
        self.dtaxisX.setFormat("MM月dd hh:mm:ss")
        #设置坐标轴上的格点
        self.dtaxisX.setTickCount(6)
        self.vlaxisY.setTickCount(11)
        #设置坐标轴名称
        self.dtaxisX.setTitleText("时间")
        self.vlaxisY.setTitleText("量程")
        #设置网格不显示
        self.vlaxisY.setGridLineVisible(False)
        #把坐标轴添加到chart中
        self.chart.addAxis(self.dtaxisX, Qt.AlignBottom)
        self.chart.addAxis(self.vlaxisY, Qt.AlignLeft)
        #把曲线关联到坐标轴
        self.series.attachAxis(self.dtaxisX)
        self.series.attachAxis(self.vlaxisY)

        self.setChart(self.chart)

    def drawLine(self):
        #获取当前时间
        bjtime = QDateTime.currentDateTime()
        #更新X轴坐标
        self.dtaxisX.setMin(QDateTime.currentDateTime().addSecs(-300 * 1))
        self.dtaxisX.setMax(QDateTime.currentDateTime().addSecs(0))
        #当曲线上的点超出X轴的范围时,移除最早的点
        if (self.series.count() > 149):
            self.series.removePoints(0, self.series.count() - 149)
        #产生随即数
        yint = random.randint(0, 1500)
        #添加数据到曲线末端
        self.series.append(bjtime.toMSecsSinceEpoch(), yint)
Exemplo n.º 10
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, weight_path, out_file_path, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("VAT ROLL COMPARE LABEL TOOL" + " " + CODE_VER)
        self.showMaximized()
        '''按键绑定'''
        # 输入媒体
        self.import_media_pushButton.clicked.connect(self.import_media)  # 导入
        self.start_predict_pushButton.clicked.connect(
            self.predict_button_click)  # 开始推理
        # 输出媒体
        self.open_predict_file_pushButton.clicked.connect(
            self.open_file_in_browser)  # 文件中显示推理视频
        # 下方
        self.play_pushButton.clicked.connect(
            self.play_pause_button_click)  # 播放
        self.pause_pushButton.clicked.connect(
            self.play_pause_button_click)  # 暂停
        self.button_dict = dict()
        self.button_dict.update({
            "import_media_pushButton": self.import_media_pushButton,
            "start_predict_pushButton": self.start_predict_pushButton,
            "open_predict_file_pushButton": self.open_predict_file_pushButton,
            "play_pushButton": self.play_pushButton,
            "pause_pushButton": self.pause_pushButton,
        })
        '''媒体流绑定输出'''
        self.input_player = QMediaPlayer()  # 媒体输入的widget
        self.input_player.setVideoOutput(self.input_video_widget)
        self.input_player.positionChanged.connect(
            self.change_slide_bar)  # 播放进度条

        self.output_player = QMediaPlayer()  # 媒体输出的widget
        self.output_player.setVideoOutput(self.output_video_widget)
        '''初始化GPU chart'''
        self.series = QSplineSeries()
        self.chart_init()
        '''初始化GPU定时查询定时器'''
        # 使用QTimer,0.5秒触发一次,更新数据
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.draw_gpu_info_chart)
        self.timer.start(500)

        # 播放时长, 以 input 的时长为准
        self.video_length = 0
        self.out_file_path = out_file_path
        # 推理使用另外一线程
        self.predict_handler_thread = PredictHandlerThread(
            self.output_player, self.out_file_path, weight_path,
            self.predict_info_plainTextEdit, self.predict_progressBar,
            self.fps_label, self.button_dict)
        # 界面美化
        self.gen_better_gui()

    def gen_better_gui(self):
        """
        美化界面
        :return:
        """
        # Play 按钮
        play_icon = QIcon()
        play_icon.addPixmap(QPixmap("./UI/icon/play.png"), QIcon.Normal,
                            QIcon.Off)
        self.play_pushButton.setIcon(play_icon)

        # Pause 按钮
        play_icon = QIcon()
        play_icon.addPixmap(QPixmap("./UI/icon/pause.png"), QIcon.Normal,
                            QIcon.Off)
        self.pause_pushButton.setIcon(play_icon)

    def chart_init(self):
        """
        初始化 GPU 折线图
        :return:
        """
        # self.gpu_info_chart._chart = QChart(title="折线图堆叠")  # 创建折线视图
        self.gpu_info_chart._chart = QChart()  # 创建折线视图
        # chart._chart.setBackgroundVisible(visible=False)      # 背景色透明
        self.gpu_info_chart._chart.setBackgroundBrush(QBrush(
            QColor("#FFFFFF")))  # 改变图背景色

        # 设置曲线名称
        self.series.setName("GPU Utilization")
        # 把曲线添加到QChart的实例中
        self.gpu_info_chart._chart.addSeries(self.series)
        # 声明并初始化X轴,Y轴
        self.dtaxisX = QDateTimeAxis()
        self.vlaxisY = QValueAxis()
        # 设置坐标轴显示范围
        self.dtaxisX.setMin(QDateTime.currentDateTime().addSecs(-300 * 1))
        self.dtaxisX.setMax(QDateTime.currentDateTime().addSecs(0))
        self.vlaxisY.setMin(0)
        self.vlaxisY.setMax(100)
        # 设置X轴时间样式
        self.dtaxisX.setFormat("hh:mm:ss")
        # 设置坐标轴上的格点
        self.dtaxisX.setTickCount(5)
        self.vlaxisY.setTickCount(10)
        # 设置坐标轴名称
        self.dtaxisX.setTitleText("Time")
        self.vlaxisY.setTitleText("Percent")
        # 设置网格不显示
        self.vlaxisY.setGridLineVisible(False)
        # 把坐标轴添加到chart中
        self.gpu_info_chart._chart.addAxis(self.dtaxisX, Qt.AlignBottom)
        self.gpu_info_chart._chart.addAxis(self.vlaxisY, Qt.AlignLeft)
        # 把曲线关联到坐标轴
        self.series.attachAxis(self.dtaxisX)
        self.series.attachAxis(self.vlaxisY)
        # 生成 折线图
        self.gpu_info_chart.setChart(self.gpu_info_chart._chart)

    def draw_gpu_info_chart(self):
        """
        绘制 GPU 折线图
        :return:
        """
        # 获取当前时间
        time_current = QDateTime.currentDateTime()
        # 更新X轴坐标
        self.dtaxisX.setMin(QDateTime.currentDateTime().addSecs(-300 * 1))
        self.dtaxisX.setMax(QDateTime.currentDateTime().addSecs(0))
        # 当曲线上的点超出X轴的范围时,移除最早的点
        remove_count = 600
        if self.series.count() > remove_count:
            self.series.removePoints(0, self.series.count() - remove_count)
        # 对 y 赋值
        # yint = random.randint(0, 100)
        gpu_info = get_gpu_info()
        yint = gpu_info[0].get("gpu_load")
        # 添加数据到曲线末端
        self.series.append(time_current.toMSecsSinceEpoch(), yint)

    def import_media(self):
        """
        导入媒体文件
        :return:
        """
        self.parameter_source = QFileDialog.getOpenFileUrl()[0]
        self.input_player.setMedia(QMediaContent(
            self.parameter_source))  # 选取视频文件

        # 设置 output 为一张图片,防止资源被占用
        path_current = str(Path.cwd().joinpath("area_dangerous\1.jpg"))
        self.output_player.setMedia(
            QMediaContent(QUrl.fromLocalFile(path_current)))

        # 将 QUrl 路径转为 本地路径str
        self.predict_handler_thread.parameter_source = self.parameter_source.toLocalFile(
        )
        self.input_player.pause()  # 显示媒体

        image_flag = os.path.splitext(
            self.predict_handler_thread.parameter_source)[-1].lower(
            ) in img_formats
        for item, button in self.button_dict.items():
            if image_flag and item in ['play_pushButton', 'pause_pushButton']:
                button.setEnabled(False)
            else:
                button.setEnabled(True)
        # self.output_player.setMedia(QMediaContent(QFileDialog.getOpenFileUrl()[0]))  # 选取视频文件

    def predict_button_click(self):
        """
        推理按钮
        :return:
        """
        # 启动线程去调用
        self.predict_handler_thread.start()

    def change_slide_bar(self, position):
        """
        进度条移动
        :param position:
        :return:
        """
        self.video_length = self.input_player.duration() + 0.1
        self.video_horizontalSlider.setValue(
            round((position / self.video_length) * 100))
        self.video_percent_label.setText(
            str(round((position / self.video_length) * 100, 2)) + '%')

    @pyqtSlot()
    def play_pause_button_click(self):
        """
        播放、暂停按钮回调事件
        :return:
        """
        name = self.sender().objectName()

        if self.parameter_source == "":
            return

        if name == "play_pushButton":
            print("play")
            self.input_player.play()
            self.output_player.play()

        elif name == "pause_pushButton":
            self.input_player.pause()
            self.output_player.pause()

    @pyqtSlot()
    def open_file_in_browser(self):
        os.system(f"start explorer {self.out_file_path}")

    @pyqtSlot()
    def closeEvent(self, *args, **kwargs):
        """
        重写关闭事件
        :param args:
        :param kwargs:
        :return:
        """
        print("Close")
Exemplo n.º 11
0
ANGULAR_MIN = -100
ANGULAR_MAX = 100

RADIAL_MIN = -100
RADIAL_MAX = 100

series1 = QScatterSeries()
series1.setName("scatter")
for i in range(ANGULAR_MIN, ANGULAR_MAX + 1, 10):
    series1.append(i, (float(i) / RADIAL_MAX) * RADIAL_MAX + 8.0)

series2 = QSplineSeries()
series2.setName("spline")
for i in range(ANGULAR_MIN, ANGULAR_MAX + 1, 10):
    series2.append(i, (float(i) / RADIAL_MAX) * RADIAL_MAX)

series3 = QLineSeries()
series3.setName("star outer")
ad = (ANGULAR_MAX - ANGULAR_MIN) / 8.0
rd = (RADIAL_MAX - RADIAL_MIN) / 3.0 * 1.3
series3.append(ANGULAR_MIN, RADIAL_MAX)
series3.append(ANGULAR_MIN + ad * 1, RADIAL_MIN + rd)
series3.append(ANGULAR_MIN + ad * 2, RADIAL_MAX)
series3.append(ANGULAR_MIN + ad * 3, RADIAL_MIN + rd)
series3.append(ANGULAR_MIN + ad * 4, RADIAL_MAX)
series3.append(ANGULAR_MIN + ad * 5, RADIAL_MIN + rd)
series3.append(ANGULAR_MIN + ad * 6, RADIAL_MAX)
series3.append(ANGULAR_MIN + ad * 7, RADIAL_MIN + rd)
series3.append(ANGULAR_MIN + ad * 8, RADIAL_MAX)
Exemplo n.º 12
0
class TotalEquityChartView(QChartView):
    """
    Chart that displays the balance between several dates
    from an account, token or whole portfolio
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.chart = QChart()

    def setupChartWithData(self, data, linecolor='#422F8A'):
        """
        Chart gets updated displaying the new data.

        Data has to be expressed on a dictionary form:
            - keys are timestamps
            - values are total balance for that timestamp
        """
        self.chart = QChart()

        self.chart.setTheme(QChart.ChartThemeDark)
        self.chart.setAnimationOptions(QChart.SeriesAnimations)
        self.chart.setBackgroundBrush(QBrush(QColor("transparent")))
        #         self.chart.setTitle("")
        #         self.chart.setTitleBrush(QBrush(QColor('white')))

        # Axis X (Dates)
        self.x_axis = QDateTimeAxis()
        self.x_axis.setTickCount(11)
        self.x_axis.setLabelsAngle(70)
        font = QFont()
        font.setFamily('Roboto')
        font.setLetterSpacing(QFont.PercentageSpacing, 110)
        font.setPointSize(8)
        self.x_axis.setLabelsFont(font)
        self.x_axis.setFormat("dd-MM-yy")
        self.x_axis.setTitleText(self.tr('Date'))
        self.x_axis.setTitleVisible(False)
        self.x_axis.setLineVisible(False)
        self.x_axis.setGridLineVisible(False)

        # Axis Y (Balances)
        self.y_axis = QValueAxis()
        if data != {}:
            self.y_axis.setMax(max(data.values()) * 1.05)
            self.y_axis.setMin(min(data.values()) * 0.95)
        # self.y_axis.setMinorGridLineVisible(False)
        self.y_axis.setLineVisible(False)
        self.y_axis.setGridLineColor(QColor("#ECE9F1"))

        self.chart.addAxis(self.y_axis, Qt.AlignLeft)
        self.chart.addAxis(self.x_axis, Qt.AlignBottom)

        # Series
        self.btcseries = QSplineSeries()
        for date in data:
            balance = data[date]
            date = QDateTime(datetime.fromtimestamp(int(float(date))))
            self.btcseries.append(date.toMSecsSinceEpoch(), balance)

        self.btcseries.setName("BTC")
        pen = QPen(QColor(linecolor))
        pen.setWidth(3)
        self.btcseries.setPen(pen)

        # Series functionality
        self.btcseries.hovered.connect(self.selectPoint)

        self.chart.addSeries(self.btcseries)
        self.btcseries.attachAxis(self.x_axis)
        self.btcseries.attachAxis(self.y_axis)

        self.setChart(self.chart)
        self.setRenderHint(QPainter.Antialiasing)
        self.setStyleSheet("border: 0px; background-color: rgba(0,0,0,0); ")

        self.chart.legend().hide()

    def selectPoint(self, point, state):
        """ Shows point where mouse is hovered """
        self.chart.setTitle(
            f"{int(point.y())} {confighandler.get_fiat_currency().upper()}")