Как передавать логин из базы данных в другие окна?
У меня есть приложение PyQt5, в котором есть форма регистрации,
после входа/регистрации логин и пароль заносятся в БД.
Мне надо чтобы значение логина могло передаваться на другие страницы (например, чтобы у каждого пользователя были свои настройки).
mainWindow.py:
class Ui_MainWindow(object):
db_start()
login = pyqtSignal(str, str)
print(login)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
MainWindow.setStyleSheet("background-color: rgb(0, 0, 0);")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(0, -40, 211, 631))
self.groupBox.setStyleSheet("background-color: rgb(255, 255, 255);")
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.pushButton = QtWidgets.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(0, 40, 211, 71))
self.pushButton.setStyleSheet("color: rgb(255, 255, 255);\n"
"font: 18pt \"MS Shell Dlg 2\";\n"
"\n"
"background-color: rgb(85, 85, 255);\n"
"image: url(:/newPrefix/199-1999586_png-file-house-icon-png.png);")
self.pushButton.setObjectName("pushButton")
self.pushButton_5 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_5.setGeometry(QtCore.QRect(0, 530, 211, 71))
self.pushButton_5.setStyleSheet("color: rgb(255, 255, 255);\n"
"font: 17pt \"MS Shell Dlg 2\";\n"
"\n"
"background-color: rgb(85, 85, 255);\n"
"image: url(:/newPrefix/199-1999586_png-file-house-icon-png.png);")
self.pushButton_5.setObjectName("pushButton_5")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(340, 10, 351, 131))
self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);\n"
"font: 16pt \"MS Shell Dlg 2\";")
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(340, 160, 351, 131))
self.pushButton_3.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);\n"
"font: 16pt \"MS Shell Dlg 2\";")
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(340, 310, 351, 131))
self.pushButton_4.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);\n"
"font: 16pt \"MS Shell Dlg 2\";")
self.pushButton_4.setObjectName("pushButton_4")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.add_functions()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setToolTip(_translate("MainWindow", "<html><head/><body><p><img src=\":/newPrefix/199-1999586_png-file-house-icon-png.png\"/></p></body></html>"))
self.pushButton.setText(_translate("MainWindow", "Home"))
self.pushButton_5.setToolTip(_translate("MainWindow", "<html><head/><body><p><img src=\":/newPrefix/199-1999586_png-file-house-icon-png.png\"/></p></body></html>"))
self.pushButton_5.setText(_translate("MainWindow", "Регистрация/вход"))
self.pushButton_2.setText(_translate("MainWindow", "Автосвап"))
self.pushButton_3.setText(_translate("MainWindow", "Выкл автосвап"))
self.pushButton_4.setText(_translate("MainWindow", f"Настройки автосвапа"))
def add_functions(self):
self.pushButton_2.clicked.connect(self.start_autoswap)
self.pushButton_3.clicked.connect(self.stop_autoswap)
self.pushButton_5.clicked.connect(self.reg)
self.pushButton_4.clicked.connect(self.settings_autoswap)
def reg(self):
self.reg = QtWidgets.QMainWindow()
self.ui = Ui_Form()
self.ui.setupUi(self.reg)
self.reg.show()
def settings_autoswap(self):
self.settings_autoswap = QtWidgets.QMainWindow()
self.ui = Ui_Settings_autoswap()
self.ui.setupUi(self.settings_autoswap)
self.settings_autoswap.show()
def start_autoswap(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
# setting message for Message Box
msg.setText("Вы хотите включить автосвап?")
# setting Message box window title
msg.setWindowTitle("Внимание!")
# declaring buttons on Message Box
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
# start the app
retval = msg.exec_()
self.autoswap_thread = threading.Thread(target=self.autoswap, daemon=True)
self.autoswap_thread.start()
def stop_autoswap(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Автосвап выключен!")
msg.setWindowTitle("Внимание!")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
self.running = False
def autoswap(self):
self.running = True
while self.running:
x = 459
y = 1402
Color = pyautogui.screenshot().getpixel((x, y))
print(Color)
if Color == (185, 185, 185):
pyautogui.press("2", presses=4, interval=0.01)
Форма входа/регистрации (из файла Form.py должно передаваться значение логина на другие страницы):
Form.py
from PyQt5 import QtCore, QtGui, QtWidgets
import database as db
from database import *
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlQueryModel
from PyQt5.QtWidgets import QMessageBox
from autoswap import *
from PyQt5.QtCore import pyqtSignal
class Ui_Form(object):
value_changed = pyqtSignal(str)
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(593, 422)
Form.setStyleSheet("background-color: rgb(0, 0, 0);")
self.groupBox = QtWidgets.QGroupBox(Form)
self.groupBox.setGeometry(QtCore.QRect(130, 40, 321, 321))
self.groupBox.setStyleSheet("background-color: rgb(42, 43, 56);")
self.groupBox.setTitle("")
self.groupBox.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox.setCheckable(False)
self.groupBox.setObjectName("groupBox")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(80, 10, 151, 61))
self.label.setStyleSheet("font: 22pt \"MS Shell Dlg 2\";\n"
"border-color: rgb(31, 32, 41);\n"
"color: rgb(255, 255, 255);")
self.label.setScaledContents(False)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit.setGeometry(QtCore.QRect(70, 120, 191, 31))
self.lineEdit.setStyleSheet("background-color: rgb(31, 32, 41);\n"
"border-color: rgb(31, 32, 41);\n"
"color: rgb(211, 211, 211);")
self.lineEdit.setText("")
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_2.setGeometry(QtCore.QRect(70, 170, 191, 31))
self.lineEdit_2.setStyleSheet("background-color: rgb(31, 32, 41);\n"
"\n"
"color: rgb(211, 211, 211);")
self.lineEdit_2.setText("")
self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit_2.setObjectName("lineEdit_2")
self.pushButton = QtWidgets.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(60, 240, 91, 41))
self.pushButton.setStyleSheet("background-color: rgb(255, 235, 167);\n"
"font: 14pt \"MS Shell Dlg 2\";\n"
"box-shadow: 0 8px 24px 0 rgb(255 235 167 / 20%);\n"
"color: rgb(94, 102, 129);")
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_2.setGeometry(QtCore.QRect(180, 240, 91, 41))
self.pushButton_2.setStyleSheet("background-color: rgb(255, 235, 167);\n"
"font: 14pt \"MS Shell Dlg 2\";\n"
"box-shadow: 0 8px 24px 0 rgb(255 235 167 / 20%);\n"
"color: rgb(94, 102, 129);")
self.pushButton_2.setObjectName("pushButton_2")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(20, 120, 47, 21))
self.label_2.setStyleSheet("font: 14pt \"MS Shell Dlg 2\";\n"
"box-shadow: 0 8px 24px 0 rgb(255 235 167 / 20%);\n"
"color: rgb(94, 102, 129);")
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.groupBox)
self.label_3.setGeometry(QtCore.QRect(10, 170, 61, 21))
self.label_3.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";\n"
"box-shadow: 0 8px 24px 0 rgb(255 235 167 / 20%);\n"
"color: rgb(94, 102, 129);")
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName("label_3")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Log IN!"))
self.pushButton.setText(_translate("Form", "Sign Up"))
self.pushButton_2.setText(_translate("Form", "Sign In"))
self.label_2.setText(_translate("Form", "Login"))
self.label_3.setText(_translate("Form", "Password"))
self.pushButton_2.clicked.connect(self.reg)
self.pushButton.clicked.connect(self.login)
def reg(self):
login = self.lineEdit.text()
self.login = login
password = self.lineEdit_2.text()
cur.execute('INSERT INTO users (login, password) VALUES (?, ?)',
(login, password))
db.commit()
msq = QMessageBox()
msq.setWindowTitle("Регистрация")
msq.setText("Вы успешно зарегистрировались!")
x = msq.exec_()
cur.execute('INSERT INTO settings_autoswap (login, coord_X, coord_y, button) VALUES (?, ?, ?, ?)',
(login, 1000, 1000, 2))
db.commit()
self.home = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.home)
self.home.show()
def login(self):
login = self.lineEdit.text()
password = cur.execute('SELECT password FROM users WHERE login = ?',
(login,)).fetchone()
if password is not None:
password_input = self.lineEdit_2.text()
for row in password:
pas = row
if pas == password_input:
msq = QMessageBox()
msq.setWindowTitle("Вход")
msq.setText("Вы успешно Вошли!")
x = msq.exec_()
elif pas != password_input:
msq = QMessageBox()
msq.setWindowTitle("Вход")
msq.setText("Неверный пароль, повторите попытку!")
x = msq.exec_()
elif password is None:
msq = QMessageBox()
msq.setWindowTitle("Вход")
msq.setText("Неверный Логин, повторите попытку!")
x = msq.exec_()
Ответы (1 шт):
Код, который вы предоставляете, должен быть воспроизводимый.
НИКОГДА НЕ ИЗМЕНЯЙТЕ код, сгенерированный Qt Designer, НИКОГДА.
Создайте другой класс, который наследуется от соответствующего виджета,
и используйте созданный класс для его заполнения.
Я сделал некоторые заметки в своем примере.
Я увидел вашу задачу так:
main.py:
import random
import sqlite3
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import pyqtSignal, QThread
from PyQt5.QtWidgets import QMessageBox
# ? from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlQueryModel
# ? from autoswap import *
# ? import database as db
# ? from database import *
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(593, 422)
Form.setStyleSheet("background-color: rgb(0, 0, 0);")
self.groupBox = QtWidgets.QGroupBox(Form)
self.groupBox.setGeometry(QtCore.QRect(130, 40, 321, 321))
self.groupBox.setStyleSheet("background-color: rgb(42, 43, 56);")
self.groupBox.setTitle("")
self.groupBox.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox.setCheckable(False)
self.groupBox.setObjectName("groupBox")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(80, 10, 151, 61))
self.label.setStyleSheet("font: 22pt \"MS Shell Dlg 2\";\n"
"border-color: rgb(31, 32, 41);\n"
"color: rgb(255, 255, 255);")
self.label.setScaledContents(False)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit.setGeometry(QtCore.QRect(70, 120, 191, 31))
self.lineEdit.setStyleSheet("background-color: rgb(31, 32, 41);\n"
"border-color: rgb(31, 32, 41);\n"
"color: rgb(211, 211, 211);")
self.lineEdit.setText("")
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_2.setGeometry(QtCore.QRect(70, 170, 191, 31))
self.lineEdit_2.setStyleSheet("background-color: rgb(31, 32, 41);\n"
"color: rgb(211, 211, 211);")
self.lineEdit_2.setText("")
self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit_2.setObjectName("lineEdit_2")
self.pushButton = QtWidgets.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(20, 240, 91, 41))
self.pushButton.setStyleSheet("background-color: rgb(255, 235, 167);\n"
"font: 14pt \"MS Shell Dlg 2\";\n"
"color: rgb(94, 102, 129);")
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_2.setGeometry(QtCore.QRect(130, 240, 170, 41))
self.pushButton_2.setStyleSheet("background-color: rgb(255, 235, 167);\n"
"font: 13pt \"MS Shell Dlg 2\";\n"
"color: rgb(94, 102, 129);")
self.pushButton_2.setObjectName("pushButton_2")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(20, 120, 47, 21))
self.label_2.setStyleSheet("font: 14pt \"MS Shell Dlg 2\";\n"
"color: rgb(94, 102, 129);")
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.groupBox)
self.label_3.setGeometry(QtCore.QRect(10, 170, 61, 21))
self.label_3.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";\n"
"color: rgb(94, 102, 129);")
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName("label_3")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Log IN!"))
self.pushButton.setText(_translate("Form", "Войти")) # Sign In
self.pushButton_2.setText(_translate("Form", "Зарегистрироваться")) # Sign Up
self.label_2.setText(_translate("Form", "Login"))
self.label_3.setText(_translate("Form", "Password"))
class Ui_MainWindow(object):
# ? db_start() # ?
# ? login = pyqtSignal(str, str) # ?
# ? print(login) # ?
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
MainWindow.setStyleSheet("background-color: rgb(0, 0, 0);")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(0, -40, 211, 631))
self.groupBox.setStyleSheet("background-color: rgb(255, 255, 255);")
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.pushButton = QtWidgets.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(0, 40, 211, 71))
self.pushButton.setStyleSheet("color: rgb(255, 255, 255);\n"
"font: 18pt \"MS Shell Dlg 2\";\n"
"\n"
"background-color: rgb(85, 85, 255);\n"
"image: url(:/newPrefix/199-1999586_png-file-house-icon-png.png);")
self.pushButton.setObjectName("pushButton")
self.pushButton_5 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_5.setGeometry(QtCore.QRect(0, 530, 211, 71))
self.pushButton_5.setStyleSheet("color: rgb(255, 255, 255);\n"
"font: 17pt \"MS Shell Dlg 2\";\n"
"\n"
"background-color: rgb(85, 85, 255);\n"
"image: url(:/newPrefix/199-1999586_png-file-house-icon-png.png);")
self.pushButton_5.setObjectName("pushButton_5")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(340, 10, 351, 131))
self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);\n"
"font: 16pt \"MS Shell Dlg 2\";")
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(340, 160, 351, 131))
self.pushButton_3.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);\n"
"font: 16pt \"MS Shell Dlg 2\";")
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(340, 310, 351, 131))
self.pushButton_4.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);\n"
"font: 16pt \"MS Shell Dlg 2\";")
self.pushButton_4.setObjectName("pushButton_4")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setToolTip(_translate("MainWindow", "<html><head/><body><p><img src=\"Ok.png\"/></p></body></html>"))
self.pushButton.setText(_translate("MainWindow", "Home"))
self.pushButton_5.setToolTip(_translate("MainWindow", "<html><head/><body><p><img src=\":/newPrefix/199-1999586_png-file-house-icon-png.png\"/></p></body></html>"))
self.pushButton_5.setText(_translate("MainWindow", "Регистрация/вход"))
self.pushButton_2.setText(_translate("MainWindow", "Автосвап"))
self.pushButton_3.setText(_translate("MainWindow", "Выкл автосвап"))
self.pushButton_4.setText(_translate("MainWindow", f"Настройки автосвапа"))
# !!! +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
class Ui_Settings_autoswap(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(400, 600)
MainWindow.setStyleSheet("background-color: rgb(77, 77, 0);")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setStyleSheet("background-color: #3aa; font-size: 25px; color: #fff;")
self.label.setText("Тут Настройки автосвапа")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.layout = QtWidgets.QVBoxLayout(self.centralwidget)
self.layout.addWidget(self.label)
self.setCentralWidget(self.centralwidget)
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# --->vvvvvvvv vvvvvvv vvvvvvv <----------------------------------------
class SignInUp(QtWidgets.QWidget, Ui_Form):
def __init__(self, parent=None): # !!! + parent
super(SignInUp, self).__init__(parent) # !!! + parent
self.setupUi(self)
self.pushButton_2.clicked.connect(self.reg)
self.pushButton.clicked.connect(self.login_sign_in)
self.lineEdit.setFocus()
self.login = None # !!! +++
self.cur = parent.cur # !!! +++
self.conn = parent.conn # !!! +++
self.parent = parent # !!! +++
def reg(self):
if (not self.lineEdit.text().strip()) or (not self.lineEdit_2.text().strip()):
msg = QtWidgets.QMessageBox.information(None,
'Внимание',
'Заполните поля входа.')
return
######
login = self.lineEdit.text()
password = self.cur.execute(
'SELECT password FROM users WHERE username = ?',
(login,)).fetchone()
#print(f'{password} ------ {not password is None}')
if not password is None:
msq = QMessageBox()
msq.setWindowTitle("Регистрация")
msq.setText(f"Пользователь с именем {login} уже зарегистрирован в БД, \n"
"повторите попытку регистрации еще раз."
)
x = msq.exec_()
return
login = self.lineEdit.text()
password = self.lineEdit_2.text()
self.cur.execute('INSERT INTO users (username, password) VALUES (?, ?)',
(login, password))
self.conn.commit()
msq = QMessageBox()
msq.setWindowTitle("Регистрация")
msq.setText("Вы успешно зарегистрировались!")
x = msq.exec_()
coord_X, coord_y, button = [random.randint(1, 1000) for _ in range(3)]
self.cur.execute('INSERT INTO settings_autoswap (login, coord_X, coord_y, button) VALUES (?, ?, ?, ?)',
(login, coord_X, coord_y, button))
self.conn.commit()
# ??? ?
''' ?????????????????????????????????
self.home = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.home)
self.home.show()
'''
# Sign In Войти
def login_sign_in(self):
if (not self.lineEdit.text().strip()) or (not self.lineEdit_2.text()):
msg = QtWidgets.QMessageBox.information(None,
'Внимание',
'Заполните поля входа.')
return
self.login = self.lineEdit.text()
password = self.cur.execute(
'SELECT password FROM users WHERE username = ?',
(self.login,)).fetchone()
if (password is None) or (password[0] != self.lineEdit_2.text()):
msq = QMessageBox()
msq.setWindowTitle("Вход")
msq.setText("Неверный Логин или пароль, \nповторите попытку! "
"или выполните регистрацию."
)
msq.exec_()
self.login = None
self.parent.pushButton_2.setEnabled(False)
self.parent.pushButton_3.setEnabled(False)
self.parent.pushButton_4.setEnabled(False)
else:
msq = QMessageBox()
msq.setWindowTitle("Вход")
msq.setText("Вы успешно Вошли!")
msq.exec_()
self.parent.successfully_logged() # !!! parent
self.close()
# --->vvvvvvvvvvvvvvvv vvvvvvvvvvv vvvvvvvvvvvvvvvvvvvv <---------------
class SettingsAutoswap(QtWidgets.QMainWindow, Ui_Settings_autoswap):
def __init__(self, parent=None): # !!! parent
super(SettingsAutoswap, self).__init__(parent) # !!! parent
self.setupUi(self)
# vvvvvv !!! parent
s_a = parent.cur.execute(
'SELECT * FROM settings_autoswap WHERE login = ?',
(parent.login,)).fetchone()
# print(s_a)
self.label.setText(f'{self.label.text()}\n\n{parent.login}\n\n{s_a}')
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
class Thread(QThread):
value_changed = pyqtSignal(str)
def __init__(self, login):
super().__init__()
self.login = login
self.running = True
def run(self, *args, **kwargs):
while self.running:
# !!! тут ваши действия, которые занимают некоторое время
'''
x = 459
y = 1402
Color = pyautogui.screenshot().getpixel((x, y))
print(Color)
if Color == (185, 185, 185):
pyautogui.press("2", presses=4, interval=0.01)
'''
c = """background-color: {};""".format(
QtGui.QColor(*random.sample(range(255), 3)).name()
)
self.value_changed.emit(c) # Излючаем сигнал и передаем аргументы подключенному слоту
self.msleep(2000) # Заставляет текущий поток спать (2000) миллисекунд msecs.
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# --->vvvvvvvvvv vvvvvvvvvvv vvvvvvvvvvvvv <----------------------------
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton_2.clicked.connect(self.start_autoswap)
self.pushButton_3.clicked.connect(self.stop_autoswap)
self.pushButton_5.clicked.connect(self.reg)
self.pushButton_4.clicked.connect(self.settings_autoswap)
self.pushButton_2.setEnabled(False)
self.pushButton_3.setEnabled(False)
self.pushButton_4.setEnabled(False)
# !!!
self.conn = sqlite3.connect('login.db')
self.cur = self.conn.cursor()
# !!!
self.login = None # !!! вот тут будет логин, который будет доступен
# !!! в любом окне вашего приложения
# +++ self.label
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(0, 120, 210, 400))
self.label.setStyleSheet("font: 12pt \"MS Shell Dlg 2\";\n"
"background-color: rgb(77, 77, 0);"
"color: rgb(255, 55, 55);")
self.label.setScaledContents(True)
self.label.setAlignment(QtCore.Qt.AlignCenter)
# "Регистрация/вход"
def reg(self):
self.reg = SignInUp(self) # !!! +++ (self)
self.reg.show()
def successfully_logged(self): # !!! +++
self.login = self.reg.login
s_a = self.cur.execute(
'SELECT * FROM settings_autoswap WHERE login = ?',
(self.login,)).fetchone()
self.label.setText(f'{self.login}\n\n{s_a}')
self.pushButton_2.setEnabled(True)
self.pushButton_4.setEnabled(True)
self.settings_autoswap = None
def settings_autoswap(self):
if self.settings_autoswap:
self.settings_autoswap.close()
self.settings_autoswap = SettingsAutoswap(self)
self.settings_autoswap.show()
def start_autoswap(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Вы хотите включить автосвап?")
msg.setWindowTitle("Внимание!")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
if retval == QtWidgets.QMessageBox.Ok:
self.autoswap()
# self.autoswap_thread = threading.Thread(target=self.autoswap, daemon=True)
# self.autoswap_thread.start()
def stop_autoswap(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Автосвап выключен!")
msg.setWindowTitle("Внимание!")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
if retval == QtWidgets.QMessageBox.Ok:
self.thread.running = False
self.pushButton_2.setEnabled(True)
self.pushButton_3.setEnabled(False)
def autoswap(self):
self.thread = Thread(self.login) # !!!
self.thread.value_changed.connect(self.slot_value_changed) # !!!
self.thread.start() # !!!
self.pushButton_2.setEnabled(False)
self.pushButton_3.setEnabled(True)
def slot_value_changed(self, value_changed):
#print(f'{value_changed}')
self.label.setStyleSheet(value_changed)
if self.settings_autoswap:
self.settings_autoswap.label.setStyleSheet(value_changed)
def closeEvent(self, event):
self.conn.close()
event.accept()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec())
Скрипт, который сформирует БД с необходимыми таблицами для тестирования, может выглядеть примерно так:
database.py:
import sqlite3
def createTable():
connection = sqlite3.connect('login.db')
connection.execute("CREATE TABLE USERS(USERNAME TEXT NOT NULL,EMAIL TEXT,PASSWORD TEXT)")
connection.execute("INSERT INTO USERS VALUES(?,?,?)",('admin','[email protected]','admin'))
connection.commit()
connection.execute("CREATE TABLE settings_autoswap(login TEXT NOT NULL, coord_X INTEGER, coord_y INTEGER, button INTEGER)")
connection.execute("INSERT INTO settings_autoswap VALUES(?,?,?,?)",('admin', 333, 333, 3))
connection.commit()
result = connection.execute("SELECT * FROM USERS")
for data in result:
print("Username : ",data[0])
print("Email : ", data[1])
print("Password :", data[2])
connection.close()
createTable()