pycharm中集成Qt desinger,并用pyqtgraph实现K线图在GUI界面中的嵌入

原文来自:https://zmister.com/archives/187.html
原文中由于缺少讲解几个import,导致代码无法跑,这里是完整的例子。

在pycharm中用QT desinger设计界面布局

关于如何将QT designer集成入pycharm中,pycharm 与 QT desinger的集成
画一个VerticalLayout层布局,如图所示,保存成example1.ui
pycharm中集成Qt desinger,并用pyqtgraph实现K线图在GUI界面中的嵌入_第1张图片

将UI文件转换为Python文件

将example1.ui转为example1.py,参见pycharm 与 QT desinger的集成

根据PyQtGraph的示例,新建一个绘制K线图的类CandlestickItem:

class CandlestickItem(pg.GraphicsObject):  
    def __init__(self, data):  
        pg.GraphicsObject.__init__(self)  
        self.data = data ## data must have fields: time, open, close, min, max  
        self.generatePicture()

    def generatePicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        w = (self.data[1][0] - self.data[0][0]) / 3.
        for (t, open, close, min, max) in self.data:
            p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
            if open > close:
                p.setBrush(pg.mkBrush('g'))
            else:
                p.setBrush(pg.mkBrush('r'))
            p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
        p.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())

创建一个函数chart(),用于通过tushare模块获取股票的历史数据,并将数据传入之前定义好的用于生成K线图的类:

这里注意安装tushare库

pip install tushare
def chart():
    hist_data = ts.get_hist_data('600519',start='2017-05-01',end='2017-11-24')
    data_list = []
    axis = []
    for dates,row in hist_data.iterrows():
        # 将时间转换为数字
        date_time = datetime.datetime.strptime(dates,'%Y-%m-%d')
        t = date2num(date_time)
        # t = dict(enumerate(datetime))
        open,high,close,low = row[:4]
        datas = (t,open,close,low,high)
        data_list.append(datas)
        axis.append(t)
    # print(axis)
    axis_dict = dict(enumerate(axis))
    item = CandlestickItem(data_list)
    plt = pg.PlotWidget()
    # print(plt.getAxis('bottom'))
    plt.addItem(item)
    plt.showGrid(x=True,y=True)
    return plt

再在example1.py文件的最后加入程序入口

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

为了能让程序跑起来,需要导入以下库

import pyqtgraph as pg
import tushare as ts
import datetime
from matplotlib.pylab import date2num

完成代码如下:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'example1.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
import pyqtgraph as pg
import tushare as ts
import datetime
from matplotlib.pylab import date2num

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(100, 30, 571, 491))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.verticalLayout.addWidget(chart())

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))


class CandlestickItem(pg.GraphicsObject):
    def __init__(self, data):
        pg.GraphicsObject.__init__(self)
        self.data = data ## data must have fields: time, open, close, min, max
        self.generatePicture()

    def generatePicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        w = (self.data[1][0] - self.data[0][0]) / 3.
        for (t, open, close, min, max) in self.data:
            p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
            if open > close:
                p.setBrush(pg.mkBrush('g'))
            else:
                p.setBrush(pg.mkBrush('r'))
            p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
        p.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())


def chart():
    hist_data = ts.get_hist_data('600519',start='2017-05-01',end='2017-11-24')
    data_list = []
    axis = []
    for dates,row in hist_data.iterrows():
        # 将时间转换为数字
        date_time = datetime.datetime.strptime(dates,'%Y-%m-%d')
        t = date2num(date_time)
        # t = dict(enumerate(datetime))
        open,high,close,low = row[:4]
        datas = (t,open,close,low,high)
        data_list.append(datas)
        axis.append(t)
    # print(axis)
    axis_dict = dict(enumerate(axis))
    item = CandlestickItem(data_list)
    plt = pg.PlotWidget()
    # print(plt.getAxis('bottom'))
    plt.addItem(item)
    plt.showGrid(x=True,y=True)
    return plt

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

效果如图
pycharm中集成Qt desinger,并用pyqtgraph实现K线图在GUI界面中的嵌入_第2张图片

你可能感兴趣的:(python)