zoukankan      html  css  js  c++  java
  • PYQT 可视化

    PYQT 实例

    import json
    import sys
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5 import QtCore
    from PyQt5.QtWidgets import *
    
    data = [{'id':'1','pairs':'EOS','price':'18'},{'id':'2','pairs':'BTC','price':'1'},{'id':'3','pairs':'USDT','price':'333'},{'id':'4','pairs':'BSV','price':'555'},{'id':'5','pairs':'BSV','price':'555'}]
    HEAD_LIST = ['id','交易队', '价格', '修改','删除','添加']
    COLUMN = len(HEAD_LIST)
    ROW = len(data)
    
    # 控制表格某列不能修改
    class EmptyDelegate(QItemDelegate):
        def __init__(self, parent):
            super(EmptyDelegate, self).__init__(parent)
    
        def createEditor(self, QWidget, QStyleOptionViewItem, QModelIndex):
            return None
    
    class TabWidget(QTabWidget,QWidget):
        def __init__(self, parent=None):
            super(TabWidget, self).__init__(parent)
            self.setWindowTitle("合约交易")
            self.resize(900,800)
    
            # 创建用于显示控件的窗口
            self.tab1 = QWidget()
            self.tab2 = QWidget()
            self.addTab(self.tab1,'选项卡1')
            self.addTab(self.tab2,'选项卡2')
            self.tableWidget = QTableWidget()
    
            self.tab1UI().init_event()
            self.tab2UI(data,self.tableWidget)
    
    ######### 页面一的所有内容 #################
        def tab1UI(self):
            layout = QFormLayout()
    
            # 浮点校验器 [-360,360],精度:小数点后2位
            doubleValidator = QDoubleValidator(self)
            doubleValidator.setRange(-360, 360)
            doubleValidator.setNotation(QDoubleValidator.StandardNotation)
            # 设置精度,小数点2位
            doubleValidator.setDecimals(2)
    
            # 大写字母和下划线
            reg = QRegExp('[A-Za-z0-9-_]+$')
            validator = QRegExpValidator(self)
            validator.setRegExp(reg)
    
            self.button = QPushButton('确定')
            self.name_label = QLabel(self.tr("委托类型"))
            self.delegate_combobox = QComboBox()
            self.delegate_combobox.addItem(self.tr('限价委托'))
            self.delegate_combobox.addItem(self.tr('跟踪委托'))
            self.delegate_combobox.addItem(self.tr('计划委托'))
            layout.addRow("委托类型", self.delegate_combobox)
    
            self.pair_name_edit = QLineEdit()
            layout.addRow('交易对', self.pair_name_edit)
            self.pair_name_edit.setPlaceholderText('字母数字下划线:ETC_USDT')
            self.pair_name_edit.setValidator(validator)
    
    
            self.price_edit = QLineEdit()
            layout.addRow('价格',self.price_edit)
            self.price_edit.setPlaceholderText('请输入浮点数')
            self.price_edit.setValidator(doubleValidator)
            self.quantity_edit = QLineEdit()
            layout.addRow('数量',self.quantity_edit)
            self.quantity_edit.setPlaceholderText('请输入浮点数')
            self.quantity_edit.setValidator(doubleValidator)
    
            self.other1_edit = QLineEdit()
            layout.addRow('其他1', self.other1_edit)
            self.other1_edit.setPlaceholderText('其他')
    
            self.other2_edit = QLineEdit()
            layout.addRow('其他2', self.other2_edit)
            self.other2_edit.setPlaceholderText('其他')
    
            self.setTabText(0,'调整参数')
            self.tab1.setLayout(layout)
            layout.addWidget(self.button)
            return self
    
        def init_event(self):
            self.button.clicked.connect(self.get_info)
    
        def get_info(self):
            delegate_type = self.delegate_combobox.currentText()
            pair_name = self.pair_name_edit.text()
            price = self.price_edit.text()
            number = self.quantity_edit.text()
            other1 = self.other1_edit.text()
            other2 = self.other2_edit.text()
            if not all([delegate_type, pair_name, price,number,other1,other2]):
                QMessageBox.about(self, '错误', '所有参数不能为空!!')
                return
    
            choice = QMessageBox.question(self, '', '确定参数正确?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if choice == 16384 :
                self.pair_name_edit.clear()
                self.price_edit.clear()
                self.quantity_edit.clear()
                self.other1_edit.clear()
                self.other2_edit.clear()
                adjust_coefficient_dict = {"委托类型": delegate_type, '交易对': pair_name, '价格': price, '数量': number,
                                           '其他1': other1, '其他2': other2}
                # with open('coefficient.txt','at',encoding='utf-8') as f:
                #     f.write(json.dumps(adjust_coefficient_dict,ensure_ascii=False)+'
    ')
                print(adjust_coefficient_dict)
    
    ######### 页面二的所有内容###################
        def tab2UI(self,data,tableWidget):
            # 当前页
            self.currentPage = 0
            # 总页数
            self.totalPage = 0
            # 总记录数
            self.totalRecrodCount = 0
            # 每页显示记录数
            self.PageRecordCount = 2
    
            # 创建窗口
            self.createWindow(tableWidget)
            # 表格数据渲染, 要根据页数进行取读数据
            self.setTableData(tableWidget,data)
    
            # 信号槽连接
            self.prevButton.clicked.connect(self.onPrevButtonClick)
            self.nextButton.clicked.connect(self.onNextButtonClick)
            self.switchPageButton.clicked.connect(self.onSwitchPageButtonClick)
    
        def createWindow(self,tableWidget):
            # 操作布局
            operatorLayout = QHBoxLayout()
            self.prevButton = QPushButton("前一页")
            self.nextButton = QPushButton("后一页")
            self.switchPageButton = QPushButton("Go")
            self.switchPageLineEdit = QLineEdit()
            self.switchPageLineEdit.setFixedWidth(40)
    
            switchPage = QLabel("转到第")
            page = QLabel("页")
            operatorLayout.addWidget(self.prevButton)
            operatorLayout.addWidget(self.nextButton)
            operatorLayout.addWidget(switchPage)
            operatorLayout.addWidget(self.switchPageLineEdit)
            operatorLayout.addWidget(page)
            operatorLayout.addWidget(self.switchPageButton)
            operatorLayout.addWidget(QSplitter())
    
            # 状态布局
            statusLayout = QHBoxLayout()
            self.totalPageLabel = QLabel()
            self.totalPageLabel.setFixedWidth(70)
            self.currentPageLabel = QLabel()
            self.currentPageLabel.setFixedWidth(70)
    
            self.totalRecordLabel = QLabel()
            self.totalRecordLabel.setFixedWidth(70)
    
            statusLayout.addWidget(self.totalPageLabel)
            statusLayout.addWidget(self.currentPageLabel)
            statusLayout.addWidget(QSplitter())
            statusLayout.addWidget(self.totalRecordLabel)
    
            self.setTabText(1, '信息展示')
            # 设置表的行,列,及表头
            tableWidget.setRowCount(ROW)
            tableWidget.setColumnCount(COLUMN)
            tableWidget.setHorizontalHeaderLabels(HEAD_LIST)
            tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
    
            # 创建界面
            layout = QVBoxLayout()
            layout.addLayout(operatorLayout)
            layout.addWidget(tableWidget)
            layout.addLayout(statusLayout)
            self.tab2.setLayout(layout)
    
        def setTableData(self,tableWidget,data):
            '''取读数据进行页面渲染'''
    
            for i in range(len(data)):
                idItem = QTableWidgetItem(data[i]['id'])
                tableWidget.setItem(i, 0, idItem)
                textItem = QTableWidgetItem(data[i]['pairs'])
                tableWidget.setItem(i, 1, textItem)
                priceItem = QTableWidgetItem(data[i]['price'])
                tableWidget.setItem(i, 2, priceItem)
    
                modifyButton = QPushButton('修改')
                modifyButton.clicked.connect(self.modify_data)
                tableWidget.setCellWidget(i, 3, modifyButton)
    
                delbutton = QPushButton('删除')
                delbutton.clicked.connect(self.delete_data)
                tableWidget.setCellWidget(i, 4, delbutton)
    
                addbutton = QPushButton('添加')
                addbutton.clicked.connect(self.add_data)
                tableWidget.setCellWidget(i, 5, addbutton)
            # 控制id列不能修改
            tableWidget.setItemDelegateForColumn(0, EmptyDelegate(self))
    
        # 添加按钮 的点击事件
        @QtCore.pyqtSlot()
        def add_data(self):
            # 点击弹出输入对话框
            id, id_ok = QInputDialog.getInt(self, 'id整数且不可重复', 'id')
            pairs, pairs_ok = QInputDialog.getText(self, '交易队名称大写', '交易队')
            price, price_ok = QInputDialog.getDouble(self, '价格浮点数', '价格',decimals=2)
    
            # 判断输入内容是否合法,不能为空,id不能重复等等。。。
            if not all([id, id_ok, pairs,pairs_ok,price,price_ok]):
                return
    
            # 产生新的行
            rowPosition = self.tableWidget.rowCount()  # 行号
            self.tableWidget.insertRow(rowPosition)
    
            self.tableWidget.setItem(rowPosition, 0, QTableWidgetItem(str(id)))
            self.tableWidget.setItem(rowPosition, 1, QTableWidgetItem(pairs))
            self.tableWidget.setItem(rowPosition, 2, QTableWidgetItem(str(price)))
            modifyButton = QPushButton('修改')
            modifyButton.clicked.connect(self.modify_data)
            self.tableWidget.setCellWidget(rowPosition, 3, modifyButton)
    
            delbutton = QPushButton('删除')
            delbutton.clicked.connect(self.delete_data)
            self.tableWidget.setCellWidget(rowPosition, 4, delbutton)
    
            addbutton = QPushButton('添加')
            addbutton.clicked.connect(self.add_data)
            self.tableWidget.setCellWidget(rowPosition, 5, addbutton)
            # 此时获得了新的数据, id, pairs, price , 更新到data文件中
            add_dic = {'id': id, 'pairs': pairs, 'price': price}
            print('新增了数据: %s'%add_dic)
    
        # 修改按钮的点击事件
        @QtCore.pyqtSlot()
        def modify_data(self):
            button = self.sender()
            key_list = ['id','pairs', 'price']
            new_dic = {}
            if button:
                row = self.tableWidget.indexAt(button.pos()).row()
                id = self.tableWidget.item(row, 0).text()
                # 通过for 循环取出该行的所有数据,修改data
                for column in range(len(key_list)):
                    content = self.tableWidget.item(row, column).text()
                    new_dic[key_list[column]] = content
                print('需要修改id为%s行,新的内容为%s'%(id,new_dic))
                # 接下来根据id修改data...
    
        # 删除按钮的点击事件
        @QtCore.pyqtSlot()
        def delete_data(self):
            button = self.sender()
            if button:
                row = self.tableWidget.indexAt(button.pos()).row()
                # 这里一定要放在删除上面,否则取出的id 出错
                id = self.tableWidget.item(row, 0).text()
                self.tableWidget.removeRow(row)
                print('删除了id为%s的行'%id)
                # 接下来删除data 中对应id的那条数据。。。
    
        def onPrevButtonClick(self):
            '''前一页按钮点击事件 '''
            pass
    
        def onNextButtonClick(self):
            '''后一页按钮点击事件'''
            pass
        def onSwitchPageButtonClick(self):
            '''go 按钮点击事件'''
            pass
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        demo = TabWidget()
        demo.show()
        sys.exit(app.exec_())
    
  • 相关阅读:
    WPF中的brushes
    com中的线程模式(转)
    线程同步
    WPF线程
    应用程序管理(Application)
    WPF的继承结构树
    HTML技巧100例(一)
    多个网站共用一个空间的超值玩法
    用JavaScript实现浏览器地震效果
    HTML技巧100例(二)
  • 原文地址:https://www.cnblogs.com/Afrafre/p/11377241.html
Copyright © 2011-2022 走看看