简体   繁体   English

Pyqt5 MainWIndow-用于连接SQL Server的简单GUI

[英]Pyqt5 MainWIndow - simple gui to connect with sql server

I need to make simple GUI which can connect with sql. 我需要制作可以与sql连接的简单GUI。

How can I pass variables from one window -> second? 如何从一个窗口->第二个窗口传递变量?

My problem is: 我的问题是:

  • I have window with login panel (QLogin.py), which is testing connection with sql server. 我有一个带有登录面板(QLogin.py)的窗口,该窗口正在测试与sql server的连接。 If it can cannect - good, log in. If not, return error. 如果可以连接-很好,请登录。如果不能,请返回错误。 It works 有用
  • In my main window (QApp.py) i need to do sql queries and return result in my qtablewidget (etc.) 在我的主窗口(QApp.py)中,我需要执行sql查询并在我的qtablewidget(等)中返回结果。
  • I wanted pass variables: login = self.username.text() & pwd = self.password.text() from QLogin to QApp to make new connection to do queries, but it doesnt work. 我想要传递变量:从QLogin到QApp传递login = self.username.text()pwd = self.password.text()进行新连接以进行查询,但是它不起作用。

Maybe someone sees better option how to solve it? 也许有人认为更好的选择是如何解决的?

To sum up: After entering IMEI in QApp.py i would like to do sql query by using credentials & connection engine from QLogin.py. 总结一下:在QApp.py中输入IMEI后,我想使用来自QLogin.py的凭据和连接引擎进行sql查询。

  • Enter sql login & password in QLogin.py 在QLogin.py中输入sql登录名和密码
  • Enter IMEI and press button -> run sql query 输入IMEI并按按钮->运行sql查询

QLogin.py QLogin.py

# -- coding: utf-8 --

from PyQt5.QtWidgets import QLineEdit,QDialogButtonBox,QFormLayout,QDialog,QMessageBox
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
import qdarkstyle
import sqlalchemy

class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super(LoginDialog,self).__init__(parent)
        self.init_ui()


    def init_ui(self):

        ### delete question mark
        self.setWindowFlags(self.windowFlags()
                            ^ Qt.WindowContextHelpButtonHint)

        ### login & password fields
        self.username = QLineEdit(self)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        loginLayout = QFormLayout()
        loginLayout.addRow("Username", self.username)
        loginLayout.addRow("Password", self.password)
        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.control)
        self.buttons.rejected.connect(self.reject)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addLayout(loginLayout)
        layout.addWidget(self.buttons)
        self.setLayout(layout)

        ### set window title & stylesheet
        self.setWindowTitle('Login Box')
        self.setWindowIcon(QtGui.QIcon('dc1.png'))
        self.setStyleSheet((qdarkstyle.load_stylesheet_pyqt5()))
        ###lock resize
        self.setSizeGripEnabled(False)
        self.setFixedSize(self.sizeHint())


    ###log by usins sql credentials
    def control(self):
        ser = ########
        base = #########
        login = self.username.text()
        pwd = self.password.text()
        timeout = 5

        self.engine = sqlalchemy.create_engine(
            "mssql+pyodbc://{username}:{pwd}@10.96.5.17\dqinstance/{dbname}?driver=SQL+Server+Native+Client+11.0".format(
                dbname=base, username=login, pwd=pwd), connect_args={'timeout': timeout})
        try:
            connection = self.engine.connect()
            connection.close()
            self.accept()
        except:
            QMessageBox.warning(self, 'Error', "Wrong username or password! \n\n"
                                               "Please use the SQL Server credentials ")

It looks like: 看起来像:

在此处输入图片说明

QApp.py QApp.py

# -- coding: utf-8 --

from PyQt5 import QtCore, QtGui, QtWidgets
from QLogin import LoginDialog
import qdarkstyle


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow,self).__init__(parent)

        self.main_frame()
        self.center() #center frame
        self.layout_init() #widgets layout

    def main_frame(self):
        ### actions on meenubar
        exitAct = QtWidgets.QAction('&Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(self.close)
        self.statusBar()

        ### menubar
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)
        fileMenu = menubar.addMenu('&Help')

        ### basic geometry and color
        self.setWindowTitle('Test Window')
        self.setWindowIcon(QtGui.QIcon('dc1.png'))
        self.setStyleSheet((qdarkstyle.load_stylesheet_pyqt5()))

    def layout_init(self):
        grid = QtWidgets.QGridLayout()
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)

        ### widgets
        self.tablewidget = QtWidgets.QTableWidget() #frame

        self.textbox = QtWidgets.QLineEdit()
        self.textbox.setPlaceholderText('IMEI')
        self.textbox.setEnabled(True)
        self.textbox.setValidator(QtGui.QDoubleValidator())

        self.pb = QtWidgets.QPushButton(self.tr("Run process"))
        self.pb.setDisabled(True)
        self.textbox.textChanged.connect(self.disableButton)
        self.pb.clicked.connect(self.on_clicked)


        ### make vidgets alive
        self.centralWidget().setLayout(grid)
        grid.addWidget(self.textbox)
        grid.addWidget(self.tablewidget)
        grid.addWidget(self.pb)

    ### center main window
    def center(self):
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def disableButton(self):
        if len(self.textbox.text())> 0:
            self.pb.setDisabled(False)
        else:
            self.pb.setDisabled(True)


    ### run process button
    def on_clicked(self):
        if len(self.textbox.text())== 0:
            pass
        else:
            print('test')

    def sql_query(self):
        self.sql = "SELECT " \
                        "FI.FileNameTransformed, " \
                        "FI.OrderItemCode, " \
                        "FIR.Imported," \
                        "FR.Row " \
                    "FROM[PROD_WAREX2].[dbo].[FileRows] FR " \
                    "JOIN[PROD_WAREX2].[dbo].[FileImportRows]FIR ON FR.RowId = FIR.RowId" \
                    "JOIN[PROD_WAREX2].[dbo].[FileImports] FI ON FIR.FileImportId = FI.Id" \
                    "WHERE FR.Row LIKE : e1"
        self.e1 = '%'&self.textbox.text()&'%'

在此处输入图片说明

QMain.py QMain.py

import sys
from PyQt5.QtWidgets import QApplication
from QLogin import LoginDialog
from QApp import MainWindow

if __name__ == '__main__':

    app = QApplication(sys.argv)

    login = LoginDialog()

    if not login.exec_():
            sys.exit(-1)

    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

The solution is simple, get credentials from login object and then pass it to window object: 解决方案很简单,从登录对象获取凭据,然后将其传递给window对象:

class LoginDialog(QDialog):
    # ...
    def credentials():
        return self.username.text(), self.password.text()
    # ...

class MainWindow(QtWidgets.QMainWindow):
    # ...

    def setCredentials(self, credentials):
        self._credentials = credentials

    # ...
    def sql_query(self):
        base = ######### 
        username, pwd = self._credentials
        self.engine = sqlalchemy.create_engine(
            "mssql+pyodbc://{username}:{pwd}@10.96.5.17\dqinstance/{dbname}?driver=SQL+Server+Native+Client+11.0".format(
                dbname=base, username=username, pwd=pwd), connect_args={'timeout': timeout})
        try:
            connection = self.engine.connect()
            # ...
        except:
            QMessageBox.warning(self, 'Error', "Wrong username or password! \n\n"
                                           "Please use the SQL Server credentials ")

if __name__ == '__main__':

    app = QApplication(sys.argv)

    login = LoginDialog()

    if login.exec_() != QtWidgets.QDialog.Accepted:
        sys.exit(-1)

    window = MainWindow()
    window.setCredentials(login.credentials()) # <----
    window.show()
    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM