我需要制作可以与sql连接的简单GUI。
如何从一个窗口->第二个窗口传递变量?
我的问题是:
login = self.username.text()
和pwd = self.password.text()
从QLogin传递到QApp,以建立新的连接以进行查询,但是它不起作用。也许有人看到了更好的解决方案?
总结:在QApp.py中输入IMEI后,我想使用来自QLogin.py的凭据和连接引擎来进行SQL查询。
# -- 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 ")
它看起来像:
# -- 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()&'%'
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_())
答案 0 :(得分:1)
解决方案很简单,从登录对象获取凭据,然后将其传递给窗口对象:
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_())