PyQt5-UI界面控件布局实战-界面水平,竖直、网格混合布局(三)

本文详细介绍了一个期货风控系统的界面设计与实现过程,包括界面布局、控件选择、功能实现等核心内容。通过 PyQt5 构建了具有高度定制化的用户界面,实现了期货账户管理、风险参数设置、行情展示等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

界面效果
在这里插入图片描述
新建risk.py文件

import json
import os
import sys

from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QPalette, QIcon
from PyQt5.QtWidgets import QTabWidget, QApplication, QTreeWidget, QTreeWidgetItem, QHBoxLayout, QLabel, QSpinBox, \
    QCheckBox, QTableWidget, QFrame, QAbstractItemView, QStyledItemDelegate, QGridLayout, QVBoxLayout, QPushButton, \
    QComboBox, QLineEdit, QWidget, QDialog, QHeaderView
from Resources import Variable


class RiskSet(QDialog):
    def __init__(self):
        super(RiskSet, self).__init__()
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.height = self.screenRect.height()
        self.width = self.screenRect.width()
        if self.width <= 1366 and self.height <= 760:
            self.setFixedSize(900, 500)
        elif self.width <= 1280 and self.height <= 960:
            self.setFixedSize(900, 500)
        else:
            self.setFixedSize(1200, 800)
        # self.Recvmsg = "RiskSet"
        # setCB(self.Recvmsg, self.recvmsgSign)  # 设置回调

        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.Tool)
        self.setModal(True)  # 设置窗口置顶
        self.currentPos = None
        self.btn2 = QPushButton()
        self.btn2.setStyleSheet('QPushButton{width:50px;height:30px;border:0px solid red;}'
                                'QPushButton::hover{background:red;color:#fff;}')

        lab = QLabel("   期货账号管理")

        self.fram = QFrame()
        self.fram.setObjectName('fram')
        self.fram.setStyleSheet(
            "#fram{border:0px solid #d6d8d7;background-color:#d4e1f8;border-bottom:0px;}")
        self.frame = QFrame()
        if os.path.isdir("../Resources"):
            self.btn2.setStyleSheet(
                'QPushButton{width:50px;height:30px;background-image:url(../Resources/Images/close2.png);background-repeat: no-repeat;border:0px;border-top-right-radius:5px;}'
                'QPushButton::hover{background-image:url(../Resources/Images/close.png);background-repeat: no-repeat;background-position:centen centen;border-top-right-radius:5px;}')
            self.setStyleSheet(
                "QComboBox{background:#fff;border:0px solid #4d4d4d;height:28px;border-radius:0px;color:black;}"
                "QComboBox QAbstractItemView{border: 1px solid #161b2e;color:#000;}"
                "QComboBox:editable{color:#000}"
                "QComboBox::down-arrow{image:url(../Resources/Images/com.png)}"
                "QComboBox::drop-down{border:0px solid;}"

            )
        else:
            self.btn2.setStyleSheet(
                'QPushButton{width:50px;height:30px;background-image:url(./Resources/Images/close2.png);background-repeat: no-repeat;border:0px;border-top-right-radius:5px;}'
                'QPushButton::hover{background-image:url(./Resources/Images/close.png);background-repeat: no-repeat;background-position:centen centen;border-top-right-radius:5px;}')
            self.setStyleSheet(
                "QComboBox{background:#fff;border:0px solid #4d4d4d;height:28px;border-radius:0px;color:black;}"
                "QComboBox QAbstractItemView{border: 1px solid #161b2e;color:#000;}"
                "QComboBox:editable{color:#000}"
                "QComboBox::down-arrow{image:url(./Resources/Images/com.png)}"
                "QComboBox::drop-down{border:0px solid;}"

            )

        hbox2 = QHBoxLayout()
        hbox2.addWidget(lab)
        hbox2.addStretch(1)
        hbox2.addWidget(self.btn2)
        hbox2.setContentsMargins(0, 0, 0, 0)

        self.fram.setLayout(hbox2)
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.fram)
        hbox3.setContentsMargins(0, 0, 0, 0)
        hbox3.setSpacing(0)

        self.tree_menu = QTreeWidget()
        self.tree_menu.header().hide()  # 隐藏表头
        self.tree_menu.setRootIsDecorated(False)
        self.tree_menu.setStyleSheet("QTreeWidget::item{height:50px;font:15px '微软雅黑'}")
        self.tree_menu.clicked.connect(self.clicked_tree_menu)

        self.tree1 = QTreeWidget()
        self.tree1.header().hide()  # 隐藏表头
        self.tree1.setStyleSheet("QTreeWidget::item{height:50px}")
        self.tree1.clicked.connect(self.clicked_tree1)

        self.tree_menu.clicked.connect(self.getriskmsg)
        self.tree1.clicked.connect(self.getriskmsg)
        # self.tree1.setRootIsDecorated(False)
        self.root_1 = QTreeWidgetItem(self.tree_menu)
        self.root_1.setText(0, '采购条件单')
        self.root_1.setExpanded(1)

        self.root_2 = QTreeWidgetItem(self.tree_menu)
        self.root_2.setText(0, '销售条件单')
        self.root_2.setExpanded(1)

        self.hbox_1 = QHBoxLayout()
        self.hbox_1.addWidget(self.tree_menu, 1)
        self.hbox_1.setContentsMargins(0, 0, 0, 0)

        self.categoryList = ['有色金属', '黑色金属', '轻工', '煤炭', '原油', '化工', '谷物', '油脂油料', '软商品', '农副']
        for m in range(len(self.categoryList)):
            root1 = QTreeWidgetItem(self.tree1)
            root1.setText(0, self.categoryList[m])
            for n in [Variable.ReturnCodeName(m)[key] for key in Variable.ReturnCodeName(m)]:
                child1 = QTreeWidgetItem(root1)
                child1.setText(0, n)
        self.hbox_2 = QHBoxLayout()
        self.hbox_2.addWidget(self.tree1, 1)
        self.hbox_2.setContentsMargins(0, 0, 0, 0)

        self.HedgingLabel = QLabel("套保比例")
        self.HedgingLabel.setStyleSheet("min-width:90px;max-width:90px;")
        self.Hedgingsp = QSpinBox()
        self.Hedgingsp.setRange(0, 100)
        self.Hedgingsp.setValue(100)
        self.symbolLabel = QLabel("%")

        self.conditioncheck = QCheckBox("条件:")
        self.label1 = QLabel("单笔交易数量超过")
        self.sp1 = QSpinBox()
        self.sp1.setRange(0, 99999999999)
        self.label2 = QLabel("启动自动套保")

        if os.path.isdir("../Resources"):
            self.Hedgingsp.setStyleSheet("QSpinBox::up-button{image:url(../Resources/Images/up.png)}"
                                         "QSpinBox::down-button{image:url(../Resources/Images/down.png)}"
                                         "QSpinBox{min-height:30px;min-width:120px;max-width:120px;}")
            self.sp1.setStyleSheet("QSpinBox::up-button{image:url(../Resources/Images/up.png)}"
                                   "QSpinBox::down-button{image:url(../Resources/Images/down.png)}"
                                   "QSpinBox{min-height:30px;min-width:120px;max-width:120px;}")

        else:
            self.Hedgingsp.setStyleSheet("QSpinBox::up-button{image:url(./Resources/Images/up.png)}"
                                         "QSpinBox::down-button{image:url(./Resources/Images/down.png)}"
                                         "QSpinBox{min-height:30px;min-width:120px;max-width:120px;}")
            self.sp1.setStyleSheet("QSpinBox::up-button{image:url(./Resources/Images/up.png)}"
                                   "QSpinBox::down-button{image:url(./Resources/Images/down.png)}"
                                   "QSpinBox{min-height:30px;min-width:120px;max-width:120px;}")

        self.accounttext = QLabel()
        self.equityLabel = QLabel("权益:")
        self.equitytext = QLabel("")
        self.usableLabel = QLabel("可用:")
        self.usabletext = QLabel("")

        self.modificationbut = QPushButton("修改")

        self.table = QTableWidget(self)  # 行情表格
        self.table.setStyleSheet("QTableWidget{background:#fff;color:yellow;border:1px solid #828790;}"
                                 "QTableCornerButton::section{background-color:#fff;}"
                                 "QTableWidget::item:selected{background:transparent;border:0px solid yellow;border-left:0px solid yellow;border-right:0px solid yellow;}"
                                 "QTableWidget::item:first:selected{border-left:0px solid yellow;}"
                                 "QTableWidget::item:last:selected{border-right:0px solid yellow;}"
                                 )  # 设置样式
        # self.table.setStyleSheet(QStringLiteral("selection-background-color: rgb(85, 255, 0);"))
        self.table.horizontalHeader().setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)  # 设置表头字体位置局左
        self.table.horizontalHeader().setStyleSheet(
            "QHeaderView::section{background:#f0f0f0;color:#000;border:1px solid #828790;border-top:0px;border-left:0px;font: '宋体';}"
            "QHeaderView::section:last{text-align: left;border-right:0px solid #8faac9;}")
        self.table.verticalHeader().setStyleSheet("QHeaderView::section{background:#003153;color:white}")
        self.table.horizontalHeader().setMinimumHeight(30)
        self.table.setFrameShape(QFrame.NoFrame)  # 无边框
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 禁止对表格编辑
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)  # 整行选择
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)  # 单选
        self.table.setItemDelegate(BackgroundDelegate(self.table))
        self.table.setMouseTracking(True)
        self.table.setShowGrid(1)  # 去表格线
        self.table.setFocusPolicy(Qt.NoFocus)  # 去除选中虚线
        self.table.horizontalHeader().setHighlightSections(0)
        self.table.verticalHeader().setVisible(0)  # 隐藏表头
        # self.table.horizontalHeader().setStretchLastSection(True)
        self.table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
        self.table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        self.table.verticalScrollBar().value()
        self.table.setColumnCount(8)  # 设置列数
        row_name = [
            "期货账户",
            "合约",
            # "比例%",
            "买卖",
            "开平",
            "价格类型",
            "价格",
            "套保",
            "操作",
        ]
        self.table.setHorizontalHeaderLabels(row_name)  # 设置行名称
        self.table.horizontalHeaderItem(6).setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.table.horizontalHeaderItem(7).setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.table.setColumnWidth(6, 58)
        # self.table.horizontalHeader().setStretchLastSection(True)
        self.table.horizontalHeader().setDefaultSectionSize(45)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(6, QHeaderView.Interactive)

        gridLayout1 = QGridLayout()
        gridLayout1.addWidget(self.HedgingLabel, 0, 0, 1, 1)
        gridLayout1.addWidget(self.Hedgingsp, 0, 1, 1, 1)
        gridLayout1.addWidget(self.symbolLabel, 0, 2, 1, 1)

        gridLayout1.addWidget(self.conditioncheck, 1, 0, 1, 1)
        gridLayout1.addWidget(self.label1, 1, 1, 1, 1)
        gridLayout1.addWidget(self.sp1, 1, 2, 1, 1)
        gridLayout1.addWidget(self.label2, 1, 3, 1, 1)

        hbox8 = QHBoxLayout()
        hbox8.addWidget(self.accounttext)
        hbox8.addWidget(self.equityLabel)
        hbox8.addWidget(self.equitytext)
        hbox8.addWidget(self.usableLabel)
        hbox8.addWidget(self.usabletext)

        gridLayout1.addItem(hbox8, 2, 0, 1, 4)
        # gridLayout1.addWidget(self.equityLabel, 2, 1, 1, 1)
        # gridLayout1.addWidget(self.equitytext, 2, 2, 1, 1)
        # gridLayout1.addWidget(self.usableLabel, 2, 3, 1, 1)
        # gridLayout1.addWidget(self.usabletext, 2, 4, 1, 1)

        self.hbox_4 = QHBoxLayout()
        self.hbox_4.addLayout(gridLayout1, 1)
        self.hbox_4.setContentsMargins(0, 0, 0, 0)

        self.hbox_5 = QHBoxLayout()
        self.hbox_5.addWidget(self.table, 1)
        self.hbox_5.setContentsMargins(0, 0, 0, 0)

        self.hbox_8 = QHBoxLayout()
        self.hbox_8.addStretch(7)
        self.hbox_8.addWidget(self.modificationbut, 1)
        self.hbox_8.setContentsMargins(0, 0, 0, 0)

        self.hbox_6 = QVBoxLayout()
        self.hbox_6.addLayout(self.hbox_4)
        self.hbox_6.addLayout(self.hbox_5, 2)
        self.hbox_6.addLayout(self.hbox_8, 1)
        self.hbox_6.setContentsMargins(0, 0, 0, 0)

        self.hbox_3 = QHBoxLayout()

        if self.width >= 1920 and self.height >= 1080:
            self.setFixedSize(1200, 800)
            self.hbox_3.addLayout(self.hbox_1, 1)
            self.hbox_3.addLayout(self.hbox_2, 2)
            self.hbox_3.addLayout(self.hbox_6, 5)
            self.hbox_3.setContentsMargins(0, 0, 0, 0)
        elif self.width >= 1360 and self.height >= 768:
            self.setFixedSize(1000, 500)
            self.hbox_3.addLayout(self.hbox_1, 1)
            self.hbox_3.addLayout(self.hbox_2, 2)
            self.hbox_3.addLayout(self.hbox_6, 8)
            self.hbox_3.setContentsMargins(0, 0, 0, 0)
        elif self.width >= 1280 and self.height >= 800:
            self.setFixedSize(1000, 500)
            self.hbox_3.addLayout(self.hbox_1, 1)
            self.hbox_3.addLayout(self.hbox_2, 2)
            self.hbox_3.addLayout(self.hbox_6, 5)
            self.hbox_3.setContentsMargins(0, 0, 0, 0)
        self.frame1 = QFrame()
        self.frame1.setObjectName("frame1")
        self.frame1.setStyleSheet("#frame1{border:0px solid red;}")
        self.frame1.setLayout(self.hbox_3)

        hbox10 = QVBoxLayout()
        hbox10.addLayout(hbox3)
        hbox10.addWidget(self.frame1, 1)
        hbox10.setContentsMargins(0, 0, 0, 0)
        hbox10.setSpacing(0)
        '''创建边框区域'''
        self.widget = QWidget()
        self.widget.setObjectName("widget")
        self.widget.setStyleSheet("#widget{border-radius:6px;background-color:#fff;}")
        self.widget.setLayout(hbox10)

        hbox9 = QHBoxLayout()
        hbox9.addWidget(self.widget)
        hbox9.setContentsMargins(0, 0, 0, 0)

        self.frame_all = QFrame()
        self.frame_all.setObjectName("frame_all")
        self.frame_all.setStyleSheet("#frame_all{border:4px solid #d4e1f8;}")
        self.frame_all.setLayout(hbox9)

        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.frame_all)
        hbox4.setContentsMargins(0, 0, 0, 0)
        '''创建边框区域'''
        self.setLayout(hbox4)

        self.futureaccount1 = QComboBox()

        self.futureaccount2 = QComboBox()
        self.code1 = QComboBox()
        self.code2 = QComboBox()
        self.ratio1 = QSpinBox()
        self.ratio1.setRange(0, 100)
        self.ratio2 = QSpinBox()
        self.direction1 = QComboBox()
        self.direction2 = QComboBox()
        self.kaiping1 = QComboBox()
        self.kaiping2 = QComboBox()
        self.price1 = QComboBox()
        self.price1spin = QSpinBox()
        self.price1spin.setHidden(1)
        self.price1spin.setRange(0, 9999999)
        self.price1edit = QLineEdit()
        self.price1edit.setStyleSheet("height:30px;border:0px;")
        self.price1edit.setEnabled(0)

        if os.path.isdir("../Resources"):
            self.price1spin.setStyleSheet("QSpinBox::up-button{image:url(../Resources/Images/up.png)}"
                                          "QSpinBox::down-button{image:url(../Resources/Images/down.png)}"
                                          "QSpinBox{min-height:30px;min-width:99px;max-width:99px;border:0px;}")

        else:
            self.price1spin.setStyleSheet("QSpinBox::up-button{image:url(./Resources/Images/up.png)}"
                                          "QSpinBox::down-button{image:url(./Resources/Images/down.png)}"
                                          "QSpinBox{min-height:30px;min-width:99px;max-width:99px;border:0px;}")

        self.widget_pric = QWidget()
        hbox = QHBoxLayout()
        hbox.addWidget(self.price1edit)
        hbox.addWidget(self.price1spin)
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.setSpacing(0)
        self.widget_pric.setLayout(hbox)

        self.price2 = QComboBox()
        self.hedging1 = QCheckBox()
        self.widget_hedging1 = QWidget()
        hbox7 = QHBoxLayout()
        hbox7.addStretch(1)
        hbox7.addWidget(self.hedging1)
        hbox7.addStretch(1)
        hbox7.setContentsMargins(0, 0, 0, 0)
        self.widget_hedging1.setLayout(hbox7)
        self.hedging2 = QCheckBox()
        self.suspendbut = QPushButton("暂停")

        self.addwidget()

        list1 = ["买", "卖"]
        self.direction1.addItems(list1)
        self.direction2.addItems(list1)

        self.price1.addItems(["市价", "限价"])
        self.price1.currentIndexChanged.connect(self.getprice)
        self.modificationbut.clicked.connect(self.submmit)
        self.suspendbut.clicked.connect(self.changestatus)
        self.btn2.clicked.connect(self.closewindow)
        self.futureaccount1.currentIndexChanged.connect(self.getmoney)

        self.Allcodenamerelation = {value: key for key, value in Variable.namedict.items()}
        self.Allcode = [Variable.AllCodename[key] for key in Variable.AllCodename]
        self.Allcodename = []
        for i in self.Allcode:
            self.Allcodename.extend(i)
        self.treemenutext = None
        self.direction = {"买": "buy", "卖": "sell"}
        self.riskstatus = {"启动": "disable", "暂停": "enable"}

    def addwidget(self):
        self.table.setRowCount(1)
        self.table.setCellWidget(0, 0, self.futureaccount1)
        # self.table.setCellWidget(1, 0, self.futureaccount2)
        self.table.setCellWidget(0, 1, self.code1)
        # self.table.setCellWidget(1, 1, self.code2)
        # self.table.setCellWidget(0, 2, self.ratio1)
        # self.table.setCellWidget(1, 2, self.ratio2)
        self.table.setCellWidget(0, 2, self.direction1)
        # self.table.setCellWidget(1, 3, self.direction2)
        self.table.setCellWidget(0, 3, self.kaiping1)
        # self.table.setCellWidget(1, 4, self.kaiping2)
        self.table.setCellWidget(0, 4, self.price1)
        self.table.setCellWidget(0, 5, self.widget_pric)
        # self.table.setCellWidget(1, 5, self.price2)
        self.table.setCellWidget(0, 6, self.widget_hedging1)
        # self.table.setCellWidget(1, 6, self.hedging2)
        self.table.setCellWidget(0, 7, self.suspendbut)
        # self.table.setCellWidget(1, 7, self.startbut)
        self.kaiping1.addItems([i for i in Variable.positiontype])
        self.price1edit.setText("市价")

    def submmit(self):
        """
        将修改完得风控信息提交
        :return:
        """
        if self.hedging1.isChecked():
            hedge = "hedge"
        else:
            hedge = "speculation"

        if self.Hedgingsp.value() == 0:
            UiPublic.LoadMsgBox("套保比例不能为0").Load()
            return
        else:
            if self.treemenutext == "采购条件单":
                risktype = "buy"
            else:
                risktype = "sell"
        if self.futureaccount1.currentText() == "":
            UiPublic.LoadMsgBox("请选择期货账号").Load()
            return
        if self.code1.currentText() == "":
            UiPublic.LoadMsgBox("请选择合约").Load()
            return
        if self.price1.currentText() == "市价":
            price = 0
        elif self.price1.currentText() == "限价":
            price = self.price1spin.value()
        if self.conditioncheck.isChecked():
            conditionenable = "enable"
            condition = self.sp1.value()
            dict = {"head": {"cmd": "setfutureriskparam", "seq": 1, "recvhandle": self.Recvmsg}, "body": [
                {"userid": Variable.Variable.user_id, "risktype": risktype,
                 "variety": Variable.ReturnVarietyID(self.codename),
                 "instrument": self.code1.currentText(),
                 "coverratio": self.Hedgingsp.value(), "conditionenable": conditionenable,
                 "condition": condition,
                 "accountid": [i["accountid"] for i in self.futureAccountList if
                               i["accountname"] == self.futureaccount1.currentText()][0],
                 # "proportion": self.ratio1.value(),
                 "side": self.direction[self.direction1.currentText()],
                 "direction": Variable.positiontype[self.kaiping1.currentText()],
                 "pricetype": Variable.pricetype[self.price1.currentText()],
                 "price": price,
                 "hedge": hedge,
                 "status": self.riskstatus[self.suspendbut.text()]}]}
        else:
            conditionenable = "disable"
            dict = {"head": {"cmd": "setfutureriskparam", "seq": 1, "recvhandle": self.Recvmsg}, "body": [
                {"userid": Variable.Variable.user_id, "risktype": risktype,
                 "variety": Variable.ReturnVarietyID(self.codename),
                 "instrument": self.code1.currentText(),
                 "coverratio": self.Hedgingsp.value(), "conditionenable": conditionenable,
                 "accountid": [i["accountid"] for i in self.futureAccountList if
                               i["accountname"] == self.futureaccount1.currentText()][0],
                 # "proportion": self.ratio1.value(),
                 "side": self.direction[self.direction1.currentText()],
                 "direction": Variable.positiontype[self.kaiping1.currentText()],
                 "pricetype": Variable.pricetype[self.price1.currentText()],
                 "price": price,
                 "hedge": hedge,
                 "status": self.riskstatus[self.suspendbut.text()]}]}
        SendCmd('{}'.format(json.dumps(dict)))

    def changestatus(self):
        """
        改变启动暂停的状态
        :return:
        """
        if self.suspendbut.text() == "启动":
            self.suspendbut.setText("暂停")
        else:
            self.suspendbut.setText("启动")

    def getprice(self):
        """
        获取价格
        :return:
        """
        try:
            if self.price1.currentText() == "市价":
                self.price1edit.setHidden(0)
                self.price1edit.setText("市价")
                self.price1spin.setHidden(1)
                self.price1val = "市价"
            else:
                self.price1edit.setHidden(1)
                self.price1spin.setHidden(0)
                # self.price1val = self.price1spin.value()
        except Exception as e:
            print(e)

    def refresh(self):
        """
        查询所有的期货账户信息
        :return:
        """
        self.futureAccounts = {
            "head": {"cmd": "queryaccountmsg", "seq": 1, "recvhandle": self.Recvmsg, "dis": "queryfuture"},
            "body": [{"querymsg": 'queryfuturetradeaccount'}]}
        self.futureAccounts = json.dumps(self.futureAccounts)
        SendCmd('{}'.format(self.futureAccounts))

    def handleMSG(self, code, msg):
        if msg == "":
            pass
        else:
            dict = eval(msg)
            if dict['head']['cmd'] == 'queryaccountmsg':  # 查询期货账号
                self.futureaccount1.clear()
                self.futureAccountList = dict['body']
                self.futureaccount1.addItems([i["accountname"] for i in self.futureAccountList])
                self.getriskmsg()  # 获取风控账号相关设置信息
            if dict["head"]["cmd"] == "setfutureriskparam":
                UiPublic.LoadMsgBox(dict["body"][0]["message"]).Load()
            if dict["head"]["cmd"] == "listFutureRiskParam":
                self.settextvalue(dict)
            if dict["head"]["cmd"] == "querycapital":
                self.equitytext.setText("")
                self.usabletext.setText("")
                if "available" in dict["body"][0]:
                    self.equitytext.setText(str(dict["body"][0]['balance']))
                    self.usabletext.setText(str(dict["body"][0]['available']))

    def clicked_tree_menu(self):
        item = self.tree_menu.currentItem()
        self.treemenutext = item.text(0)

    def clicked_tree1(self):
        if self.treemenutext == None:
            item1 = self.tree_menu.topLevelItem(0)
            self.tree_menu.setCurrentItem(item1)
            self.treemenutext = item1.text(0)
        self.code1.clear()
        item = self.tree1.currentItem()
        self.codename = self.retutncodename(item.text(0))
        if self.codename in self.Allcodenamerelation:
            self.code1.addItems([i for i in self.Allcodename if self.Allcodenamerelation[self.codename] ==
                                 ''.join([x for x in i if x.isalpha()])])

    def retutncodename(self, text):
        if text == "铜":
            return "沪铜"
        elif text == "铝":
            return "沪铝"
        elif text == "锌":
            return "沪锌"
        elif text == "铅":
            return "沪铅"
        elif text == "镍":
            return "沪镍"
        elif text == "锡":
            return "沪锡"
        else:
            return text

    def getriskmsg(self):
        """
        获取风控信息
        :return:
        """
        if self.treemenutext != None and self.code1.currentText() != "":
            if self.treemenutext == "采购条件单":
                risktype = "buy"
            else:
                risktype = "sell"
            SendCmd('{}'.format(json.dumps({
                "head": {"cmd": "listFutureRiskParam", "seq": 1, "recvhandle": self.Recvmsg},
                "body": [{"risktype": risktype, "variety": Variable.ReturnVarietyID(self.codename)}]})))

    def settextvalue(self, dict):
        """
        将风控信息显示
        :return:
        """
        try:
            if dict["body"][0]["mainorderlist"] == []:
                self.code1.setCurrentIndex(0)
                self.cleartextvalue()
                self.futureaccount1.setCurrentIndex(0)
                self.conditioncheck.setChecked(0)
                self.direction1.setCurrentText("买")
                self.kaiping1.setCurrentText("开仓")
                self.price1.setCurrentText("市价")
                self.getprice()
                self.hedging1.setChecked(0)
                self.suspendbut.setText("启动")
                return
            self.code1.setCurrentText(dict["body"][0]["mainorderlist"][0]["instrument"])
            self.futureaccount1.setCurrentText(dict["body"][0]["mainorderlist"][0]["accountname"])
            self.Hedgingsp.setValue(float(dict["body"][0]["mainorderlist"][0]["coverratio"]))
            if dict["body"][0]["mainorderlist"][0]["conditionenable"] == 'enable':
                self.conditioncheck.setChecked(1)
                self.sp1.setValue(float(dict["body"][0]["mainorderlist"][0]["condition"]))
            else:
                self.conditioncheck.setChecked(0)
            # self.ratio1.setValue(float(dict["body"][0]["mainorderlist"][0]["proportion"]))
            self.direction1.setCurrentText(
                {value: key for key, value in self.direction.items()}[dict["body"][0]["mainorderlist"][0]["side"]])
            self.kaiping1.setCurrentText(
                {value: key for key, value in Variable.positiontype.items()}[
                    dict["body"][0]["mainorderlist"][0]["direction"]])
            self.price1.setCurrentText(
                {value: key for key, value in Variable.pricetype.items()}[
                    dict["body"][0]["mainorderlist"][0]["pricetype"]])
            if self.price1.currentText() == "市价":
                self.price1edit.setText("市价")
            elif self.price1.currentText() == "限价":
                self.price1spin.setValue(float(dict["body"][0]["mainorderlist"][0]["price"]))
            if dict["body"][0]["mainorderlist"][0]["hedge"] == "hedge":
                self.hedging1.setChecked(1)
            else:
                self.hedging1.setChecked(0)
            if dict["body"][0]["mainorderlist"][0]["status"] == "enable":
                self.suspendbut.setText("暂停")
            else:
                self.suspendbut.setText("启动")
        except Exception as e:
            print(e)

    def cleartextvalue(self):
        self.Hedgingsp.setValue(100)
        self.sp1.setValue(0)
        # self.ratio1.setValue(0)
        self.price1spin.setValue(0)

    def getmoney(self):
        """
        设置权益和可用
        :return:
        """
        self.accounttext.setText(self.futureaccount1.currentText())
        for i in self.futureAccountList:
            if i["accountname"] == self.futureaccount1.currentText():
                self.getcapital(i["accountid"], i["brokerid"], i["accountname"])

    def getcapital(self, accountid, brokerid, accountname):
        SendCmd('{}'.format(json.dumps({
            "head": {"cmd": "querycapital", "seq": 1, "recvhandle": self.Recvmsg},
            "body": [{"accountid": accountid, "brokerid": brokerid, "accountname": accountname,
                      "password": 123}]})))

    def closewindow(self):
        self.close()

    def mousePressEvent(self, event):
        self.currentPos = event.pos()

    def mouseMoveEvent(self, event):
        try:
            self.move(QPoint(self.pos() + event.pos() - self.currentPos))
        except Exception as e:
            pass


class BackgroundDelegate(QStyledItemDelegate):
    def __init__(self, tb, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.tb = tb

    def paint(self, painter, styleOptionViewItem, modelIndex):
        new_option = styleOptionViewItem
        row = modelIndex.row()
        column = modelIndex.column()
        item = self.tb.item(row, column)
        if item:
            color = item.foreground().color()
            new_option.palette.setColor(QPalette.HighlightedText, color)
        super().paint(painter, styleOptionViewItem, modelIndex)


if __name__ == '__main__':
    # 创建应用程序和对象
    app = QApplication(sys.argv)
    ex = RiskSet()
    ex.show()
    sys.exit(app.exec_())

新建variable.py文件

  import json

from Main.WebsocketClient.setting import SendCmd

b1 = b'tcp://180.168.146.187:10000'
b2 = b'tcp://180.168.146.187:10010'
codedict = {'cu': '沪铜', 'al': '沪铝', 'zn': '沪锌', 'pb': '沪铅', 'ni': '沪镍', 'sn': '沪锡'}
namedict = {}
autohedgedict = {1: '已套保', 2: '未套保'}
ordertypedict = {1: '市价', 2: '总价', 3: '一口价', 4: '期货价'}
invoicetypedict = {1: '当月发票', 2: '次月发票'}
paymenttypedict = {1: '现货现款', 2: '定金尾款'}
deliverytypedict = {1: '买家自提', 2: '提单过户', 3: '卖家送货'}
senddeliverytypedict = {'买家自提': 1, '提单过户': 2, '卖家送货':3 }
discounttypedict = {1: '固定升贴水', 2: '浮动升贴水', 3: '一口价'}
volumetypedict = {1: '定向', 2: '库存',3:'自由'}
quotestatusdict = {1: '销售中', 2: '已暂停', 3: '已售罄', 4: '已撤单', 5: '默认销售中'}
pcontractstatus = {1: '待上传', 2: '已上传'}
ppaymentstats = {1: '待发送', 2: '待付款', 3: '待确认收款', 4: '待付定金', 5: '待确认定金', 6: '待付尾款', 7: '待确认尾款', 8: '已付款'}
pdeliverystatus = {1: '待处理', 2: '待传提货信息', 3: '可提货', 4: '出库'}
scontractstatus = {1: '待上传', 2: '以上传'}
spaymentstats = {1: '未发送', 2: '待付款', 3: '待确认收款', 4: '待付定金', 5: '待确认定金', 6: '待付尾款', 7: '待确认尾款', 8: '已付款'}
sdeliverystatus = {1: '待传信息', 2: '待处理', 3: '可提货', 4: '入库'}
contracttype = {1: '甲方合同', 2: '乙方合同'}
searchtype = {1: '升贴水', 2: '一口价'}
hedgestatusdict = {-1: '未发送', 0: '委托中', 1: '全部撤单', 2: '部分成交', 3: '全部成交', 4: '废单', 5: '过期', 6: '部分撤单'}
orderstatusdict = {1: '请求挂单', 2: '同意挂单', 3: '拒绝挂单', 4: '已撤单', 5: '已成交', 6: '交易中', 7: '部分撤单', 8: '过期'}
Buyingselling = {1: '多', 2: '空'}
Kaiping = {1: '开仓', 2: '平仓', 3: '平今',4:'平昨',5:'自动平仓',6:'自动开平'}
RoleDict = {"管理员":1,"部门经理":2, "业务员":4, "仓储员":8, "档案员":16,"风控员":32,"交易员":64}
errors = {-106:'连接超时',-102:'仓位不足', 1: '交易所返回废单', 2: '会话信息不一致', 3: '不合法的登录',4: '用户不活跃', 5: '重复的登录', 6: '还没有登录', 7: '还没有初始',8: '前置不活跃', 9: '无此权限', 10: '修改别人的口令', 11: '找不到该用户', 12: '找不到该经纪公司', 13: '找不到投资者', 14: '原口令不匹配', 15: '报单字段有误', 16: '找不到合约', 17: '合约不能交易', 18: '经纪公司不是交易所的会员', 19: '投资者不活跃', 20: '投资者未在交易所开户', 21: '该交易席位未连接到交易所', 22: '报单错误:不允许重复报单',
         23: '错误的报单操作字段', 24: '撤单已报送,不允许重复撤单', 25: '撤单找不到相应报单', 26: '报单已全成交或已撤销,不能再撤', 27: '不支持的功能', 28: '没有报单交易权限', 29: '只能平仓', 30: '平仓量超过持仓量', 31: '资金不足', 32: '主键重复', 33: '找不到主键', 34: '设置经纪公司不活跃状态失败', 35: '经纪公司正在同步', 36: '经纪公司已同步', 37: '现货交易不能卖空', 38: '不合法的结算引用', 39: '交易所网络连接失败', 40: '交易所未处理请求超过许可数', 41: '交易所每秒发送请求数超过许可数', 42: '结算结果未确认', 43: '没有对应的入金记录',
         44: '交易所已经进入连续交易状态', 45: '找不到预埋(撤单)单', 46: '预埋(撤单)单已经发送', 47: '预埋(撤单)单已经删除', 48: '无效的投资者或者密码', 49: '不合法的登录IP地址', 50: '平今仓位不足', 51: '平昨仓位不足', 52: '经纪公司没有足够可用的条件单数量', 53: '投资者没有足够可用的条件单数量', 54: '经纪公司不支持条件单', 55: '重发未知单经济公司/投资者不匹配', 56: '同步动态令牌失败', 57: '动态令牌校验错误', 58: '找不到动态令牌配置信息', 59: '不支持的动态令牌类型', 60: '用户在线会话超出上限', 61: '该交易所不支持套利/做市商类型报单', 62: '没有条件单交易权限', 63: '客户端认证失败', 64: '客户端未认证',
         65: '该合约不支持互换类型报单', 66: '该期权合约只支持投机类型报单', 67: '执行宣告错误,不允许重复执行', 68: '重发未知执行宣告经纪公司/投资者不匹配', 69: '只有期权合约可执行', 70: '该期权合约不支持执行', 71: '执行宣告字段有误', 72: '执行宣告撤单已报送,不允许重复撤单', 73: '执行宣告撤单找不到相应执行宣告', 74: '执行仓位不足', 75: '连续登录失败次数超限,登录被禁止', 76: '非法银期代理关系', 77: '无此功能', 78: '发送报单失败', 79: '发送报单操作失败', 80: '交易所不支持的价格类型', 81: '错误的执行类型', 82: '无效的组合合约', 83: '无效的组合合约', 84: '重发未知报价经纪公司/投资者不匹配', 85: '该合约不支持报价',
         86: '报价撤单找不到相应报价', 87: '该期权合约不支持放弃执行', 88: '该组合期权合约只支持IOC', 89: '打开文件失败', 90: '查询未就绪,请稍后重试', 91: '交易所返回的错误', 92: '报价衍生单要等待交易所返回才能撤单', 93: '找不到组合合约映射', 94: '', 95: '', 96: '', 97: '', 98: '', 99: '', 100: '', 101: '用户在本系统没有报单权限', 102: '系统缺少灾备标示号', 103: '该交易所不支持批量撤单', 104: '', 105: '',
         106: '投资者限仓', 113: '当前时间禁止询价', 114: '当前价差禁止询价',116: '下单频率限制', 131: '您当前密码为弱密码,请修改成强密码后重新登录',139: '当前时间禁止行权', 140: '首次登录必须修改密码,请修改密码后重新登录', 141: '您当前密码已过期,请修改后登录', 142: '修改密码失败。新密码不允许与旧密码相同', 143: '您登录失败次数过多,IP被禁止登入CTP', 144: '您当前IP在黑名单中,被禁止登入CTP'}

positiontype = {"开仓":"open","平仓":"close","平今": "closetoday","自动":"autoopenclose"}
pricetype = {"限价":"limit","市价":"market"}

nonferrousmetals = {"cu":"铜","al":"铝","zn":"锌","pb":"铅","ni":"镍","sn":"锡"}
ferrousmetal = {"rb":"螺纹","i":"铁矿","hc":"热卷","wr":"线材","SF":"硅铁","SM":"锰硅"}
lightindustry = {"FG":"玻璃","sp":"纸浆","fb":"纤板","bb":"胶板"}
coal = {"jm":"焦煤","j":"焦炭","ZC":"动煤"}
rawpetroleum = {"fu":"燃油","sc":"原油"}
Chemical = {"bu":"沥青","ru":"橡胶","l":"塑料","TA":"PTA","v":"PVC","eg":"乙二醇","MA":"甲醇","pp":"聚丙烯"}
cereal = {"c":"玉米","cs":"淀粉","WH":"强麦","PM":"普麦","RI":"早稻","JR":"粳稻","LR":"晚稻"}
Greaseoil = {"a":"豆一","b":"豆二","m":"豆粕","y":"豆油","RS":"菜籽","RM":"菜粕","OI":"菜油","p":"棕榈"}
Softcommodities = {"CF":"棉花","SR":"白糖","CY":"棉纱"}
agricultural = {"jd":"鸡蛋","AP":"苹果"}
AllCodename ={}
listvarietyclassification = {}
varietydict = {"上期所SHFE": ["沪铜", "沪铝", "沪锌", "沪铅", "沪镍", "沪锡", "螺纹", "线材", "热卷", "燃油", "沥青", "橡胶", "纸浆"],
                  "大商所DCE": ["豆粕", "豆油", "豆一", "豆二", "棕榈", "玉米", "淀粉", "鸡蛋", "胶板", "纤板", "塑料",
                          "PVC", "乙二醇", "聚丙烯", "焦炭", "焦煤", "铁矿"],
        "郑商所CZCE": ["白糖", "棉花", "玻璃", "PTA", "强麦", "普麦", "早稻", "晚稻", "粳稻", "菜籽", "菜油", "菜粕", "硅铁", "锰硅", "苹果"],
        "上期能源INE": ["原油"]
                   }
accounttype = {"期货": 1, "外盘": 2, "现货": 3, }
class Variable:
    currentorderpage = 0  # 点价小标签页
    currentModuleTab = 0  # 模块 页码
    currentCategoryTab = 0  # 点价 金属种类 页码
    currentStockDepartIndex = 0
    authkey = 0
    accesskey = 0
    password = 0
    loginname = 0
    user_id = 0
    nickname = 0
    company_id = 0
    permission = 0
    roleid = 0
    deptid  = 0
    department = 0
    userid = 0
    userpw = 0
    logined = False  # 表示是否已经登录
    logincount=0  # 记录登录次数,超过3次就放弃
    primarymenu = []
    additionalmenu = []  # 判断有没有品类品牌导入导出权限
    stockdeptid = 0  # 仅供仓库模块使用得部门id
    # 记住密码
    cb = 1


def ReturnName(varietyname):
    if varietyname == "铜":
        varietyname = "沪铜"
    elif varietyname == "铝":
        varietyname = "沪铝"
    elif varietyname == "锌":
        varietyname = "沪锌"
    elif varietyname == "铅":
        varietyname = "沪铅"
    elif varietyname == "镍":
        varietyname = "沪镍"
    elif varietyname == "锡":
        varietyname = "沪锡"

    elif varietyname == "沪铜":
        varietyname = "铜"
    elif varietyname == "沪铝":
        varietyname = "铝"
    elif varietyname == "沪锌":
        varietyname = "锌"
    elif varietyname == "沪铅":
        varietyname = "铅"
    elif varietyname == "沪镍":
        varietyname = "镍"
    elif varietyname == "沪锡":
        varietyname = "锡"
    return varietyname


def ReturnVarietyID(varietyname):
    """
    :param varietyname: 小品种对应的英文名或者中文名
    :return: 小品种对应的代号varietyid
    """
    codename = {"铜":"沪铜","铝":"沪铝","锌":"沪锌","铅":"沪铅","镍":"沪镍","锡":"沪锡","郑棉":"棉花","郑煤":"动煤","EG":"乙二醇"
                ,"郑醇":"甲醇","PP":"聚丙烯","郑麦":"强麦","郑油":"菜油"}
    if varietyname in codename:
        varietyname = codename[varietyname]
    for i in listvarietyclassification:
        if varietyname == i["varietyname"] or varietyname == i["varietyshortname"]:
            return str(i["varietyid"])


def ReturnVarietyName(varietyid):
    """
    :param varietyid: 小品种对应的id
    :return: 小品种对应的name
    """
    varietyid = int(varietyid)
    for i in listvarietyclassification:
        if varietyid == i["varietyid"]:
            if i["varietyname"] == "沪铜":
                varietyname = "铜"
            elif i["varietyname"] == "沪铝":
                varietyname = "铝"
            elif i["varietyname"] == "沪锌":
                varietyname = "锌"
            elif i["varietyname"] == "沪铅":
                varietyname = "铅"
            elif i["varietyname"] == "沪镍":
                varietyname = "镍"
            elif i["varietyname"] == "沪锡":
                varietyname = "锡"
            else:
                varietyname = i["varietyname"]
            return varietyname


def GetUserInfo(recvhandle):
    # 查询报价抬头
    SendClientCmd({"head": {"cmd": "updatespotuserifno", "seq": 1, "recvhandle":recvhandle, "dis": "query"},
                   "body": [{"op": "query"}]})


def GetCategBrand(recvhandle,rights):
    SendClientCmd({"head": {"cmd": "querytcategbrand", "seq": 1, "recvhandle": recvhandle},
                              "body": [{"rights":rights,"deptid":Variable.deptid}]})


def GetCustomer(recvhandle):
    # 查询好友列表
    SendClientCmd({"head": {"cmd": "sendcustomermsg", "seq": 1, "recvhandle":recvhandle},
                       "body": [{"loginname": Variable.loginname}]})


def SendClientCmd(cmd):
    cmd["body"][0]["speciesid"] = Variable.currentCategoryTab+1
    SendCmd("{}".format(json.dumps(cmd)))


def ReturnCodeName(id):
    if id == 0:
        return nonferrousmetals
    elif id ==1:
        return ferrousmetal
    elif id ==2:
        return lightindustry
    elif id ==3:
        return coal
    elif id ==4:
        return rawpetroleum
    elif id ==5:
        return Chemical
    elif id ==6:
        return cereal
    elif id ==7:
        return Greaseoil
    elif id ==8:
        return Softcommodities
    elif id ==9:
        return agricultural


def returnexchid(codename):
    """

    :param codename:
    :return: exchid
    """
    for i in listvarietyclassification:
        if i["varietyshortname"] == codename:
            return i["exchid"]


def returntradeunit(codename):
    """

    :param codename:
    :return: tradeunit
    """
    for i in listvarietyclassification:
        if i["varietyshortname"] == codename:
            return i["tradeunit"]
### Python与PyQt5的集成 #### 创建简单应用程序 为了展示Python与PyQt5的集成,下面是一个创建简单GUI应用程序的例子。此例子会构建一个基础的应用框架并显示一个带有按钮的小窗口。 ```python import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout class SimpleApp(QWidget): def __init__(self): super().__init__() # 设置窗口属性 app_layout = QVBoxLayout() # 使用垂直布局管理器 button = QPushButton('点击这里', self) button.clicked.connect(self.on_click) app_layout.addWidget(button) self.setLayout(app_layout) self.setWindowTitle('简易PyQt5 App') def on_click(self): print("按钮被按下") if __name__ == '__main__': application = QApplication(sys.argv) main_window = SimpleApp() main_window.show() try: sys.exit(application.exec_()) except SystemExit as e: pass ``` 这段代码定义了一个名为`SimpleApp`的类继承自`QWidget`[^2]。该类初始化时设置了应用的基本结构——包括添加一个按钮到界面上以及连接按钮点击事件到指定的方法上。当运行这个脚本的时候,会出现一个小窗体,其中有一个可点击的按钮;一旦用户点击它,则会在控制台打印一条消息表示响应操作[^3]。 #### 布局管理和控件介绍 在上述实例中已经涉及到了最基本的布局方式之一:`QVBoxLayout`用于沿竖直方向排列子部件。除此之外还有其他类型的布局水平布局(`QHBoxLayout`)网格布局(`QGridLayout`)等可用于更复杂的设计需求。对于界面中的各个元素(即控件),像标签(QLabel)、编辑框(QLineEdit)、复选框(QCheckBox)都是用来增强用户体验的重要组成部分,在实际项目里可以根据具体场景灵活选用合适的组件来满足特定的功能要求。 #### 进阶特性支持 除了基本的操作之外,PyQt5还提供了许多高级特性和功能模块供开发者利用。比如表格视图(QTableView)适合处理大量数据项列表的情况;而多线程机制则有助于改善大型程序性能表现,防止因长时间任务阻塞主线程而导致UI无响应现象的发生。另外,借助于信号与槽机制能够方便地实现不同对象间的通信协作,使得整个系统的架构更加清晰合理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宥钧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值