Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带有SQL server和自定义类的qSqlQueryModel_Python_Pyqt5 - Fatal编程技术网

Python 带有SQL server和自定义类的qSqlQueryModel

Python 带有SQL server和自定义类的qSqlQueryModel,python,pyqt5,Python,Pyqt5,我正在尝试制作一个完全基于SQL server的应用程序。5个月后,当我尝试使用qtableView的“qSqlQueryModel”时,我意识到我的应用程序结构是错误的。因此,我需要一个专家解决方案来系统地安排应用程序。我尝试了很多方法,也阅读了文档。但我不知道我哪里做错了 我使用Designer创建布局。以下是我的项目结构: Application |---connection | |----connection.py

我正在尝试制作一个完全基于SQL server的应用程序。5个月后,当我尝试使用qtableView的“qSqlQueryModel”时,我意识到我的应用程序结构是错误的。因此,我需要一个专家解决方案来系统地安排应用程序。我尝试了很多方法,也阅读了文档。但我不知道我哪里做错了

我使用Designer创建布局。以下是我的项目结构:

Application
          |---connection
          |            |----connection.py
          |
          |---CSS ---css.py
          |
          |---EventHandler----acc_EventHandler.py
          |
          |---InterFaces ----acc_layout.py (converted from .ui)
          |
          |---Resources
          |           |--fonts
          |           |--icons
          |           |--qrc
          |
          |__mainApp.py
          |
          |__acc_view.py
当应用程序打开时,将创建db连接。在db连接建立后,用户可以从表单的Input方法中搜索值。这是一个完全基于查询的应用程序,我使用tabWidget实现不同的方法。我在
接口
文件夹中存储了许多布局,如acc_layout.py和acc_EventHandler.py是我分别编写SQL查询的相应文件。
acc_view.py
是视图部分

这是我的代码部分,可能是错误的:

附件视图.py

from PyQt5.QtWidgets import QTableView, QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QMenu,QTableWidgetItem
import resources.qrc_account
import resources.qrc_billing
import sys
from files.interfaces.acc_layout import Ui_BillingWindow
from event_handler.acc_Eenthandler import *
from css.billing_css import * 
from connection.connection import *
from PyQt5.QtSql import QSqlDatabase, QSqlQuery,QSqlTableModel,QSqlQueryModel
from PyQt5.QtCore import QModelIndex, Qt

class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, table_data, parent=None):
    QtCore.QAbstractTableModel.__init__(self, parent)
    self.table_data = table_data

def rowCount(self, parent,QModelIndex_parent=None, *args, **kwargs):
    return len(self.table_data)

def columnCount(self, parent):
    return len(self.table_data[0])

def flags(self, index):
    original_flags = super(MyTableModel, self).flags(index)
    return original_flags | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

def data(self, index, role=QtCore.Qt.DisplayRole):
    if role == QtCore.Qt.DisplayRole:
        row = index.row()
        column = index.column()
        item = index.internalPointer()
        if item is not None:
            print(item)
        value = self.table_data[row][column]
        return value

 class accMainWindow(QtWidgets.QWidget,Ui_BillingWindow):
def __init__(self, parent=None):
    super(billingMainWindow, self).__init__(parent)
   
    self.setupUi(self)
    self.tabWidget.setStyleSheet(stylesheet2)
    self.pushButton_FeeTran.clicked.connect(self.insightAccountCall)<----self function call


def insightAccountCall(self):
    print("Loading insight Account datas...")    
    
    input_value=self.account_lineEdit.text()
    type_value=str(self.account_comboBox.currentText())

    self.table = QtWidgets.QTableView()
   
    data=loadInsightAccount(input_value,type_value) <-----function call loadInsightAccount from acc_Eventhandler
    print(data)
    self.model = MyTableModel(data)
    self.tableView.setModel(self.model)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = accMainWindow()
    w.show()
    sys.exit(app.exec_())
from PyQt5 import QtCore, QtGui, QtWidgets
from  PyQt5.QtWidgets import *

def loadInsightAccount(input_value,type_value):

    print(input_value)
    print(type_value)

            if type_value=="Account Number":
        print("Account Number")
        
        query_string="SELECT  convert(int,iinsightaccountid) as AccountID, *  from InsightAccounts.dbo.InsightAccount(nolock) where vchCustodianAccountNumber like"+"'%"+ input_value +"%'"
        # print(query_string)

        InsightAcc_data=displayData(query_string) <--call function displayData from connection.py

        return (InsightAcc_data)
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
from PyQt5.QtWidgets import QTableView, QApplication,QMessageBox, QLabel
import sys
from PyQt5.QtCore import Qt, QTimer

def onActivated(self,text):
   
    createConnection(self, text)

USERNAME = ''
PASSWORD = ''
DATABASE = ''

def selectedServer(server):
    switcher = {
        'TFUS3 (UAT)': 'DESKTOP-4TB7NOA',
        'TFUSD (test)': '8888888888888',
    }
    return switcher.get(server, "Invalid Server ")

def createConnection(self, server):

    SERVER = selectedServer(server)
    global db
    db = QSqlDatabase.addDatabase('QODBC')
    db.setDatabaseName(f'Driver={{SQL SERVER}}; Server={SERVER}; UID={USERNAME}; PWD={PASSWORD};')
    if db.open():
        print(f'{server} Server connected successfully')
        # qApp.setStyleSheet("QMessageBox {background-color: #364392;}")
        
        QMessageBox.about(self, 'Connection',f'{server} Server connected successfully')
        # QMessageBox.information(self, 'Notification', 'connected', QMessageBox.Ok) 
        return True
    else:
        print(f'{server} connection failed')
        return False

def displayData(sqlStatement):
    print('processing query...')
    qry = QSqlQuery(db)
    qry.prepare(sqlStatement)
    print(sqlStatement)
    qry.exec()
    # result = cursor.fetchall() 

    model = QSqlQueryModel()
    model.setQuery(qry)
  
    return model  <---may be wrong approach
从PyQt5.qtwidts导入QTableView,QApplication
从PyQt5导入QtCore、QtGui、QtWidgets
从PyQt5.QtWidgets导入QApplication、QWidget、QPushButton、QMenu、QTableWidgetItem
导入resources.qrc_帐户
导入资源。qrc_计费
导入系统
从files.interfaces.acc_布局导入Ui_计费窗口
从event_handler.acc_Eenthandler导入*
从css.billing\u css导入*
从connection.connection导入*
从PyQt5.QtSql导入QSqlDatabase、QSqlQuery、QSqlTableModel、QSqlQueryModel
从PyQt5.QtCore导入QModelIndex,Qt
类MyTableModel(QtCore.QAbstractTableModel):
def uuu init uuu(self,table_data,parent=None):
QtCore.QAbstractTableModel.\uuuu init\uuuu(self,parent)
self.table_data=table_data
def行数(self、parent、QModelIndex_parent=None、*args、**kwargs):
返回长度(自表_数据)
def列数(自身、父项):
返回len(self.table\u数据[0])
def标志(自、索引):
原始_flags=super(MyTableModel,self).flags(索引)
返回原始|u标志| QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def数据(self,index,role=QtCore.Qt.DisplayRole):
如果角色==QtCore.Qt.DisplayRole:
行=索引。行()
column=index.column()
item=index.internalPointer()
如果项目不是无:
打印(项目)
值=自身。表_数据[行][列]
返回值
类accMainWindow(QtWidgets.QWidget,Ui_BillingWindow):
def uuu init uuu(self,parent=None):
超级(BillingMain窗口,自).\u初始化\u(父级)
self.setupUi(self)
self.tabWidget.setStyleSheet(样式表2)

self.butdown_FeeTran.clicked.connect(self.insightAccountCall)首先,请修复代码摘录上的缩进(请参阅)。那么,将这么多相关和孤立的函数拆分成这么多文件的原因是什么?这对性能和项目设计都没有帮助,只会让维护变得非常麻烦。此外,还有许多函数引用了
self
,但它们似乎不是类的一部分。这背后需要什么?@musicamante感谢您的宝贵建议。我会关注代码的格式。您能给我展示一个带有自定义类的qSqlQueryModel的完美示例,其中db连接和视图位于两个不同的文件中。