从MainWin类外访问PyQt5对象。

问题描述 投票:0回答:1

我正在开发一个读取MS Access DBs的应用程序,以产生提取和数据操作到SharePoint。 我面临的一个挑战是,我需要编写一个冗长的GUI界面,其中包含许多简单的事件。 为了保持代码的有序性,我将编写子程序并导入到主程序中。因此,会有一些代码需要在类外运行,并在类内访问对象。 我在确定正确的语法方面遇到了问题。

或者有什么方法可以直接导入到类中以避免重新定义的问题?

在InitUI中,有一个叫做TestIt()的子例程的调用,在这个子例程中,我打印了一条消息来验证代码是否被调用。 然后我尝试从主窗口设置单行编辑对象的文本值。 问题是正确的调用方式是什么? 我是否需要重新定义变量。

主程序是这样的。

from PyQt5 import QtCore, QtGui, QtWidgets
from Main import Ui_MainWin
import sys, time, os, configparser
import pyodbc
from ServerQueue import *

class MainWindow_EXEC():
    def __init__(self):             # This section has to be laid out this way 
        app = QtWidgets.QApplication(sys.argv)
        win = QtWidgets.QMainWindow()

        self.ui = Ui_MainWin()
        self.ui.setupUi(win) 
        self.initUI()               # Inits that need to happen before start up

        win.setWindowTitle("This is the Title!")
        #win.resize(800,600)
        win.show()  
        sys.exit(app.exec_()) 

    def initUI(self):
        TestIt()
        self.ui.cmbAppCodes.currentIndexChanged.connect(self.selectionchange)
        try:
            self.conn = pyodbc.connect(r'Driver={Microsoft Access Driver
            (*.mdb,*.accdb)};DBQ='+ dbPath + ';',autocommit=True)
            self.cursor = self.conn.cursor()
        except:
            print("Error opening the database!")
            qApp.quit()
        print(dbPath)
        self.loadAppCodes()

    def loadAppCodes(self):
        self.ui.cmbAppCodes.clear()
        sql = "SELECT [App Code], [App Name] from [App List] ORDER BY [App Code];"
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        for code in res:
            self.ui.cmbAppCodes.addItem("{} - {}".format(code[0], code[1]))

    def selectionchange(self,i):
        App = self.ui.cmbAppCodes.itemText(i)
        sql = "SELECT * FROM [LCM Application List] WHERE [App Code] = '" + App[0:3] + "';"
        self.cursor.execute(sql)
        res = self.cursor.fetchone()

        self.ui.lneAPM.setText(res[3])
        self.ui.lneTPM.setText(res[21])
        self.ui.lneAPO.setText(res[4])

#-----------------------------------------------------------------------------
# Load up the init file
#-----------------------------------------------------------------------------
def iniSettings():
    if sys.platform == "win32":
        os.system('cls')
        Home = os.path.expanduser('~') + "\\"
        D = "W"
    else:
        os.system('clear')
        Home = os.path.expanduser('~') + "/"
        D = "O"

    config = configparser.ConfigParser()
    config.read(Home + 'LCM.ini')           # Path to LCM.ini file

    Configs = config['DEFAULT']             # Read the DEFAULT section
    return [Home, Configs['LCMDB'], Configs['CR1'], D]


##########################################################################################
# Main Body
###########################################################################################
if __name__ == "__main__":
    Paths = iniSettings() # This is to pull the ini data for paths and what not.
    hmPath = Paths[0]
    dbPath = Paths[1]
    cr1Path = Paths[2]
    myOS = Paths[3] 

    print("Home:     {}\nCR1:      {}\nDatabase: {}\n".format(hmPath, cr1Path, dbPath))

    MainWindow_EXEC() # Becuase the init is laid out this way this is all that is needed
    print("Application completed")enter code here



#This file is imported and is called ServerQueue.py
def TestIt():
    print("TestIt")
    self.ui.lneAPM.setText("Testing")

#-----------------------------------------------------------------------------
# Main Processing Loop
#-----------------------------------------------------------------------------
if __name__ == "__main__":
    print("\n ********* \n This file is not meant to be run directly! \n ********* \n")
python pyqt pyqt5
1个回答
0
投票

你做的一切都在倒退。您试图让业务逻辑的元素消耗GUI,但正确的逻辑是相反的。GUI消耗业务逻辑元素的信息。考虑到上述情况,Test()函数不应该直接修改GUI,而是向GUI提供信息,实现的方法之一是返回文本。

def TestIt():
    print("TestIt")
    return "Testing"
# ...

def initUI(self):
    self.ui.lneAPM.setText(TestIt())
    # ...

如果上面的方法不能解决问题,那么你可能有一个 XY问题 所以我建议你把你的问题重新写得更好,提供一个更好的。MRE

© www.soinside.com 2019 - 2024. All rights reserved.