I am trying to build a simple internet speed test app using pyqt5
I am a beginner and trying to build small apps to learn GUI basics So here is the code whenever i try to change label text from my thread function is says that self has no member named label_7. ignore the print statements i was just using them for debugging
def Update_values(self,MainWindow):
_translate = QtCore.QCoreApplication.translate
self.label_7.setText(_translate("MainWindow", "Download Speed : " + str(down)))
at the upper part of code i got error
Thank you in advance
from PyQt5 import QtCore, QtGui, QtWidgets
import speedtest as st
speed_test = st.Speedtest()
download = speed_test.download()
val = 0
val1 = 0
val3 = 0
down = 0
up = 0
pin = 0
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(331, 307)
font = QtGui.QFont()
font.setFamily("Lucida Sans Unicode")
MainWindow.setFont(font)
MainWindow.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
MainWindow.setMouseTracking(False)
MainWindow.setTabletTracking(False)
MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
MainWindow.setDocumentMode(False)
MainWindow.setTabShape(QtWidgets.QTabWidget.Triangular)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(16)
self.label.setFont(font)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 3)
self.line_2 = QtWidgets.QFrame(self.centralwidget)
self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.gridLayout.addWidget(self.line_2, 1, 0, 1, 3)
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 2)
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setFrameShape(QtWidgets.QFrame.NoFrame)
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 3, 0, 1, 2)
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 2)
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setObjectName("label_7")
self.gridLayout.addWidget(self.label_7, 5, 0, 1, 2)
self.label_8 = QtWidgets.QLabel(self.centralwidget)
self.label_8.setObjectName("label_8")
self.gridLayout.addWidget(self.label_8, 6, 0, 1, 1)
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setProperty("value", 24)
self.progressBar.setTextVisible(False)
self.progressBar.setObjectName("progressBar")
self.gridLayout.addWidget(self.progressBar, 7, 0, 1, 3)
self.check1 = QtWidgets.QCheckBox(self.centralwidget)
self.check1.setObjectName("check1")
self.check1.stateChanged.connect(self.check_1)
self.gridLayout.addWidget(self.check1, 8, 0, 1, 1)
self.check2 = QtWidgets.QCheckBox(self.centralwidget)
self.check2.setObjectName("check2")
self.check2.stateChanged.connect(self.check_2)
self.gridLayout.addWidget(self.check2, 8, 1, 1, 1)
self.check3 = QtWidgets.QCheckBox(self.centralwidget)
self.check3.setObjectName("check3")
self.check3.stateChanged.connect(self.check_3)
self.gridLayout.addWidget(self.check3, 8, 2, 1, 1)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.start_test)
self.gridLayout.addWidget(self.pushButton, 9, 0, 1, 3)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 331, 22))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuAbout = QtWidgets.QMenu(self.menubar)
self.menuAbout.setObjectName("menuAbout")
MainWindow.setMenuBar(self.menubar)
self.actionSave_Results = QtWidgets.QAction(MainWindow)
self.actionSave_Results.setCheckable(False)
self.actionSave_Results.setChecked(False)
self.actionSave_Results.setObjectName("actionSave_Results")
self.actionChange_Save_Directory = QtWidgets.QAction(MainWindow)
self.actionChange_Save_Directory.setObjectName("actionChange_Save_Directory")
self.actionDeveloper = QtWidgets.QAction(MainWindow)
self.actionDeveloper.setObjectName("actionDeveloper")
self.menuFile.addAction(self.actionSave_Results)
self.menuFile.addAction(self.actionChange_Save_Directory)
self.menuAbout.addAction(self.actionDeveloper)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuAbout.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Internet Speed Test"))
self.label.setText(_translate("MainWindow", "Internet Speed Test By FATE"))
self.label_2.setText(_translate("MainWindow", "Status : Connected"))
self.label_4.setText(_translate("MainWindow", "Ping : --"))
self.label_3.setText(_translate("MainWindow", "Upload Speed : --"))
self.label_7.setText(_translate("MainWindow", "Download Speed : --"))
self.label_8.setText(_translate("MainWindow", "Progress :"))
self.check1.setText(_translate("MainWindow", "Download"))
self.check2.setText(_translate("MainWindow", "Upload"))
self.check3.setText(_translate("MainWindow", "Ping"))
self.pushButton.setText(_translate("MainWindow", "Start"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuAbout.setTitle(_translate("MainWindow", "About"))
self.actionSave_Results.setText(_translate("MainWindow", "Save Results"))
self.actionChange_Save_Directory.setText(_translate("MainWindow", "Change Save Directory"))
self.actionDeveloper.setText(_translate("MainWindow", "Developer"))
self.Update_values(MainWindow)
def Update_values(self,MainWindow):
_translate = QtCore.QCoreApplication.translate
self.label_7.setText(_translate("MainWindow", "Download Speed : " + str(down)))
# self.label_7.setText(_translate("MainWindow", "Download Speed : 10"))
print(down)
print(up)
print(pin)
def check_1(self, state):
global val
print(val)
if state != self.check1.isChecked():
val += 1
print("YESH "+ str(val))
else:
val -= 1
print("NO" + str(val))
def check_2(self, state):
global val1
print(val1)
if state != self.check1.isChecked():
val1 += 1
print("YESH "+ str(val1))
else:
val1 -= 1
print("NO" + str(val1))
def check_3(self, state):
global val3
print(val3)
if state != self.check1.isChecked():
val3 += 1
print("YESH "+ str(val3))
else:
val3 -= 1
print("NO" + str(val3))
def start_test(self):
self.threadclass = Thread()
self.threadclass.start()
class Thread(QtCore.QThread,Ui_MainWindow):
def __init__(self,parent = None):
super(Thread, self).__init__(parent)
def run(self):
if val == 1:
download = speed_test.download()
download_mbs = round(download / (10**6), 2)
global down
down = download_mbs
self.Update_values(Ui_MainWindow)
if val1 == 1:
upload = speed_test.upload()
upload_mbs = round(upload / (10**6), 2)
global up
up = upload_mbs
if val3 == 1:
ping = speed_test.results.ping
global pin
pin = ping
print("DONE")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
First of all, you should not modify the code generated by Qt Designer, so in my next solution you must regenerate the .py generated by pyuic and call it gui.py: python -m pyuic5 your_ui.ui -o gui.py.
Another error you have is that you should not update the GUI from another thread, nor use global variables since they are prone to generating silent errors, instead you should use the signals as shown below:
from enum import Flag, auto
import threading
from PyQt5 import QtCore, QtGui, QtWidgets
import speedtest
from gui import Ui_MainWindow
class Task(Flag):
NONE = auto()
DOWNLOAD = auto()
UPLOAD = auto()
PING = auto()
class SpeedtestWrapper(QtCore.QObject):
started = QtCore.pyqtSignal()
finished = QtCore.pyqtSignal()
downloaded = QtCore.pyqtSignal(float)
uploaded = QtCore.pyqtSignal(float)
pinged = QtCore.pyqtSignal(float)
def start(self, flag):
threading.Thread(target=self._execute, args=(flag,), daemon=True).start()
def _execute(self, flag):
self.started.emit()
speed_test = speedtest.Speedtest()
if flag & Task.DOWNLOAD:
download = speed_test.download()
download_mbs = round(download / (10 ** 6), 2)
self.downloaded.emit(download_mbs)
if flag & Task.DOWNLOAD:
upload = speed_test.upload()
upload_mbs = round(upload / (10 ** 6), 2)
self.uploaded.emit(upload_mbs)
if flag & Task.DOWNLOAD:
ping = speed_test.results.ping
self.pinged.emit(ping)
self.finished.emit()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self._flag = Task.NONE
self.speed_wrapper = SpeedtestWrapper()
self.speed_wrapper.started.connect(self.on_started)
self.speed_wrapper.finished.connect(self.on_finished)
self.speed_wrapper.downloaded.connect(self.on_downloaded)
self.speed_wrapper.uploaded.connect(self.on_uploaded)
self.speed_wrapper.pinged.connect(self.on_pinged)
#QtCore.pyqtSlot()
def start_test(self):
if self._flag != Task.NONE:
self.speed_wrapper.start(self._flag)
#QtCore.pyqtSlot(int)
def check_1(self, state):
if state:
self._flag |= Task.DOWNLOAD
else:
self._flag &= ~Task.DOWNLOAD
#QtCore.pyqtSlot(int)
def check_2(self, state):
if state:
self._flag |= Task.UPLOAD
else:
self._flag &= ~Task.UPLOAD
#QtCore.pyqtSlot(int)
def check_3(self, state):
if state:
self._flag |= Task.PING
else:
self._flag &= ~Task.PING
#QtCore.pyqtSlot()
def on_started(self):
self.label_7.setText(self.tr("Download Speed: --"))
self.label_3.setText(self.tr("Upload Speed: --"))
self.label_4.setText(self.tr("Ping Speed: --"))
self.pushButton.setEnabled(False)
#QtCore.pyqtSlot()
def on_finished(self):
self.pushButton.setEnabled(True)
#QtCore.pyqtSlot(float)
def on_downloaded(self, download):
self.label_7.setText(self.tr("Download Speed: %f" % download))
#QtCore.pyqtSlot(float)
def on_uploaded(self, upload):
self.label_3.setText(self.tr("Upload Speed: %f" % upload))
#QtCore.pyqtSlot(float)
def on_pinged(self, ping):
self.label_4.setText(self.tr("Ping Speed: %f" % ping))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Related
This question already has answers here:
Qt 4: Move window without title bar
(2 answers)
Closed 2 years ago.
I am trying to make an image viewer in PyQt5 with Python.
So far I have the functionality I want at the moment, this is a matter of styling the GUI how I would like it.
It looks almost how I want it.
I struggled to get that transparentish background, but managed to by setting windowflags to FramelesswindowHint. Unfortunately, now I don't have a menubar to close the application if I want to and drag the window around. I figure I will have to craft my own bar if I want to style it in a way that suits my background, which is fine, adding an X button to close the window shouldn't be too much of an issue.
My question is, how do I make it so I can drag the window around? I could make a rectangle widget and position it at the top with my buttons, but how do I get the whole window to move if the user clicks and drags it? I know similar questions are around, but I'm not sure how to make click and drag functions yet on objects in PyQt5 and it seems they use different layout strategies so I'm finding them confusing.
Here is my code:
from PyQt5 import QtCore, QtGui, QtWidgets
import os
class Ui_MainWindow(object):
def __init__(self):
cwd = r"C:\Users\chees\PycharmProjects\PYQT5GUI\images"
self.imagelist = []
self.imagepaths = []
self.imagecount = 0
for a, b, c in os.walk(cwd):
self.imagelist = c
for i in c:
self.imagepaths.append(a + "\\" + i)
print(self.imagepaths)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowModality(QtCore.Qt.NonModal)
MainWindow.resize(661, 580)
MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground)
MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.b = QtWidgets.QWidget(self.centralwidget)
self.b.setGeometry(QtCore.QRect(0, 0, MainWindow.width(), MainWindow.height()))
self.b.setStyleSheet("background-color: rgba(0, 0, 0, 70%); border:1px; border-radius:25px;")
self.imageviewer = QtWidgets.QLabel(self.centralwidget)
self.imageviewer.setGeometry(QtCore.QRect(170, 60, 351, 321))
self.imageviewer.setText("")
self.imageviewer.setPixmap(QtGui.QPixmap("images/IMG1.jpg"))
self.imageviewer.setScaledContents(True)
self.imageviewer.setObjectName("imageviewer")
self.backward_button = QtWidgets.QPushButton(self.centralwidget)
self.backward_button.setGeometry(QtCore.QRect(50, 471, 120, 50))
self.backward_button.setObjectName("backward_button")
self.backward_button.clicked.connect(self.backward)
self.forward_button = QtWidgets.QPushButton(self.centralwidget)
self.forward_button.setGeometry(QtCore.QRect(510, 470, 120, 50))
self.forward_button.setObjectName("forward_button")
self.forward_button.clicked.connect(self.forward)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
self.statusbar.setStyleSheet("background-color: rgba(255,255,255, 40%)")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.changesize()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.backward_button.setText(_translate("MainWindow", "<<"))
self.forward_button.setText(_translate("MainWindow", ">>"))
def changesize(self):
self.imageviewer.adjustSize()
if self.imageviewer.width() < 500:
MainWindow.resize(500, self.imageviewer.height() + 200)
self.b.resize(500, self.imageviewer.height() + 200)
self.imageviewer.move((500-self.imageviewer.width())//2, 55)
else:
MainWindow.resize((self.imageviewer.width() + self.imageviewer.width() // 8), (self.imageviewer.height() + 200))
self.b.resize((self.imageviewer.width() + self.imageviewer.width() // 8),
(self.imageviewer.height() + 200))
self.imageviewer.move(self.imageviewer.width() // 16, 55)
self.forward_button.move(MainWindow.width()-150,MainWindow.height()-80)
self.backward_button.move(30, MainWindow.height() - 80)
self.statusbar.showMessage(self.imagepaths[self.imagecount])
def flipmode(self):
self.imageviewer.setPixmap(QtGui.QPixmap("images\\" + self.imagelist[self.imagecount]))
self.changesize()
print(self.imageviewer.height(), self.imageviewer.width())
def forward(self):
self.imagecount += 1
if self.imagecount == len(self.imagelist):
self.imagecount = 0
self.flipmode()
def backward(self):
self.imagecount -= 1
if self.imagecount < 0:
self.imagecount = len(self.imagelist)-1
self.flipmode()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
print(ui.imagelist)
sys.exit(app.exec_())
Do not modify the code generated by Qt Designer but create another class that inherits
from the appropriate widget and use the initial class to fill it.
One of the ways to drag a window might look like this:
self._old_pos = None
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self._old_pos = event.pos()
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self._old_pos = None
def mouseMoveEvent(self, event):
if not self._old_pos:
return
delta = event.pos() - self._old_pos
self.move(self.pos() + delta)
from PyQt5 import QtCore, QtGui, QtWidgets
import os
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowModality(QtCore.Qt.NonModal)
MainWindow.resize(661, 580)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.b = QtWidgets.QWidget(self.centralwidget)
self.b.setGeometry(QtCore.QRect(0, 0, MainWindow.width(), MainWindow.height()))
self.b.setStyleSheet("background-color: rgba(0, 0, 0, 70%); border:1px; border-radius:25px;")
self.imageviewer = QtWidgets.QLabel(self.centralwidget)
self.imageviewer.setGeometry(QtCore.QRect(170, 60, 351, 321))
self.imageviewer.setText("")
self.imageviewer.setPixmap(QtGui.QPixmap("images/IMG1.jpg"))
self.imageviewer.setScaledContents(True)
self.imageviewer.setObjectName("imageviewer")
self.backward_button = QtWidgets.QPushButton(self.centralwidget)
self.backward_button.setGeometry(QtCore.QRect(50, 471, 120, 50))
self.backward_button.setObjectName("backward_button")
self.backward_button.clicked.connect(self.backward)
self.forward_button = QtWidgets.QPushButton(self.centralwidget)
self.forward_button.setGeometry(QtCore.QRect(510, 470, 120, 50))
self.forward_button.setObjectName("forward_button")
self.forward_button.clicked.connect(self.forward)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
self.statusbar.setStyleSheet("background-color: rgba(255,255,255, 40%)")
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.backward_button.setText(_translate("MainWindow", "<<"))
self.forward_button.setText(_translate("MainWindow", ">>"))
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
# cwd = r"C:\Users\chees\PycharmProjects\PYQT5GUI\images"
cwd = "D:/_Qt/__Qt/images"
self.imagelist = []
self.imagepaths = []
self.imagecount = 0
for a, b, c in os.walk(cwd):
self.imagelist = c
for i in c:
self.imagepaths.append(a + "\\" + i)
#print(self.imagepaths)
self.changesize()
#++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
self._old_pos = None
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self._old_pos = event.pos()
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self._old_pos = None
def mouseMoveEvent(self, event):
if not self._old_pos:
return
delta = event.pos() - self._old_pos
self.move(self.pos() + delta)
# ++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
def changesize(self):
self.imageviewer.adjustSize()
if self.imageviewer.width() < 500:
self.resize(500, self.imageviewer.height() + 200)
self.b.resize(500, self.imageviewer.height() + 200)
self.imageviewer.move((500-self.imageviewer.width())//2, 55)
else:
self.resize((self.imageviewer.width() + self.imageviewer.width() // 8), (self.imageviewer.height() + 200))
self.b.resize((self.imageviewer.width() + self.imageviewer.width() // 8),
(self.imageviewer.height() + 200))
self.imageviewer.move(self.imageviewer.width() // 16, 55)
self.forward_button.move(self.width()-150, self.height()-80)
self.backward_button.move(30, self.height() - 80)
self.statusbar.showMessage(self.imagepaths[self.imagecount])
def flipmode(self):
self.imageviewer.setPixmap(QtGui.QPixmap("images\\" + self.imagelist[self.imagecount]))
self.changesize()
# print(self.imageviewer.height(), self.imageviewer.width())
def forward(self):
self.imagecount += 1
if self.imagecount == len(self.imagelist):
self.imagecount = 0
self.flipmode()
def backward(self):
self.imagecount -= 1
if self.imagecount < 0:
self.imagecount = len(self.imagelist)-1
self.flipmode()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
# MainWindow = QtWidgets.QMainWindow()
# ui = Ui_MainWindow()
# ui.setupUi(MainWindow)
# MainWindow.show()
w = MainWindow()
w.show()
# print(ui.imagelist)
sys.exit(app.exec_())
I have been creating an application that through a task. the application constantly throws data at me and shows it to the table, however, having so much information, the application hangs for me at times. I was searching the web and I found this question:
Update QTableWidget rows with each iteration of loop
actually I was using QTableWidget I just used QTableView but it didn't work. the effect i want on my table is similar to this script
import time
for i in range(100000):
print(i)
time.sleep(0.3)
I leave my PyQT5 code:
table.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(492, 403)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.txt_quantity = QtWidgets.QLineEdit(self.centralwidget)
self.txt_quantity.setObjectName("txt_quantity")
self.horizontalLayout.addWidget(self.txt_quantity)
self.btn_run = QtWidgets.QPushButton(self.centralwidget)
self.btn_run.setObjectName("btn_run")
self.horizontalLayout.addWidget(self.btn_run)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.table = QtWidgets.QTableView(self.centralwidget)
self.table.setObjectName("table")
self.gridLayout.addWidget(self.table, 1, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 492, 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.label.setText(_translate("MainWindow", "quantity: "))
self.btn_run.setText(_translate("MainWindow", "run"))
main.py
import sys
import time
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from table import Ui_MainWindow
class main(QMainWindow):
def __init__(self):
super(main, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.table()
self.ui.txt_quantity.setText("100000")
self.ui.btn_run.clicked.connect(self.run)
def run(self):
for i in range(int(self.ui.txt_quantity.text())):
item1 = QStandardItem("item" + str(i))
item1.setTextAlignment(Qt.AlignCenter)
item2 = QStandardItem("item" + str(i))
item2.setTextAlignment(Qt.AlignCenter)
item3 = QStandardItem("item" + str(i))
item3.setTextAlignment(Qt.AlignCenter)
item4 = QStandardItem("item" + str(i))
item4.setTextAlignment(Qt.AlignCenter)
item5 = QStandardItem("item" + str(i))
item5.setTextAlignment(Qt.AlignCenter)
self.model.appendRow([item1, item2, item3, item4, item5])
self.ui.table.setModel(self.model)
# optional the effect I want
time.sleep(0.3)
def table(self):
self.model = QStandardItemModel()
self.model.setColumnCount(5)
self.model.setRowCount(0)
self.model.setHorizontalHeaderLabels(['header1', 'header2', 'header3', 'header4', 'header5'])
self.ui.table.setModel(self.model)
self.ui.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.ui.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
self.ui.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
self.ui.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
self.ui.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.Stretch)
if __name__ == '__main__':
app = QApplication([])
application = main()
application.show()
sys.exit(app.exec())
thank you very much community :)
You should not use time.sleep() since it blocks the event loop, in this case you can substitute the for-loop + time.sleep() with an iterator + QTimer.
class main(QMainWindow):
def __init__(self):
super(main, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.table()
self.ui.txt_quantity.setText("100000")
self.ui.btn_run.clicked.connect(self.run)
self.iter = None
self.timer = QTimer(interval=300, timeout=self.add_row)
def run(self):
try:
rows = int(self.ui.txt_quantity.text())
except ValueError:
print("The value entered must be a integer")
else:
if rows > 0:
self.iter = iter(range(rows))
self.add_row()
self.timer.start()
else:
print("The value entered must be a positive integer")
def add_row(self):
try:
i = next(self.iter)
except StopIteration:
self.iter = None
self.timer.stop()
else:
item1 = QStandardItem("item" + str(i))
item1.setTextAlignment(Qt.AlignCenter)
item2 = QStandardItem("item" + str(i))
item2.setTextAlignment(Qt.AlignCenter)
item3 = QStandardItem("item" + str(i))
item3.setTextAlignment(Qt.AlignCenter)
item4 = QStandardItem("item" + str(i))
item4.setTextAlignment(Qt.AlignCenter)
item5 = QStandardItem("item" + str(i))
item5.setTextAlignment(Qt.AlignCenter)
self.model.appendRow([item1, item2, item3, item4, item5])
def table(self):
# ...
I have a form with to labels (clock on the top and running string on the bottom). I added linker_by_grid to form (so that all components can proportional resize when form resize).
When I run project, every seconds text in running string is twitching. If I delete linker_by_grid from form, everything is OK, but all components not autoresizing to form.
Code from QtDesigner:
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(498, 299)
self.verticalLayoutWidget = QtWidgets.QWidget(Form)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 479, 281))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_2.setFont(font)
self.label_2.setText("")
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.tableWidget = QtWidgets.QTableWidget(self.verticalLayoutWidget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.verticalLayout.addWidget(self.tableWidget)
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label.setFont(font)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
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", "Running string ... "))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_()) ```
main file:
``` from PyQt5 import QtWidgets
from PyQt5.QtCore import QTimer, QTime
import sys
import untitled
class Widget(QtWidgets.QWidget):
def __init__(self):
super(Widget, self).__init__()
self.ui = untitled.Ui_Form()
self.ui.setupUi(self)
self.x = 477
self.y = self.height() - 30
self.ui.label.move(self.x, self.y)
self.timer = QTimer(self)
self.timer.timeout.connect(self.move_label_left)
self.timer.start(100)
self.timer2 = QTimer(self)
self.timer2.timeout.connect(self.show_clock)
self.timer2.start(1000)
def move_label_left(self):
if self.x == -477:
self.x = 477
self.x -= 2
self.ui.label.move(self.x, self.height() - 30)
else:
self.x -= 2
self.ui.label.move(self.x, self.height() - 30)
def show_clock(self):
time = QTime.currentTime()
text = time.toString('hh:mm:ss')
self.ui.label_2.setText(text)
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_()) ```
You need to remove the label from the layout
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import QtWidgets
from PyQt5.QtCore import QTimer, QTime
#import untitled
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(500, 350) #(498, 299)
# self.verticalLayoutWidget = QtWidgets.QWidget(Form)
# self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 479, 281))
# self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(Form) #(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 50) # + 50
self.verticalLayout.setObjectName("verticalLayout")
self.label_2 = QtWidgets.QLabel(Form) #(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_2.setFont(font)
self.label_2.setText("")
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.tableWidget = QtWidgets.QTableWidget(Form) #(self.verticalLayoutWidget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(4)
self.tableWidget.setRowCount(3)
self.verticalLayout.addWidget(self.tableWidget)
# self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
# font = QtGui.QFont()
# font.setPointSize(15)
# self.label.setFont(font)
# self.label.setObjectName("label")
# self.verticalLayout.addWidget(self.label)
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", "Running string ... "))
class Widget(QtWidgets.QWidget):
def __init__(self):
super(Widget, self).__init__()
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.tableWidget.setAlternatingRowColors(True) # +
self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) # +
self.labelMove = QtWidgets.QLabel("Running string ... ", self) # +
font = QtGui.QFont() # +
font.setPointSize(15) # +
self.labelMove.setFont(font) # +
self.x = self.width() #477
self.y = self.height() - 30
self.labelMove.move(self.x, self.y)
self.timer = QTimer(self)
self.timer.timeout.connect(self.move_label_left)
self.timer.start(15) # 100
self.timer2 = QTimer(self)
self.timer2.timeout.connect(self.show_clock)
self.timer2.start(1000)
def move_label_left(self):
if self.x <= -150: # 477
self.x = self.width() # 477
self.x -= 1
self.labelMove.move(self.x, self.height() - 30)
else:
self.x -= 1
self.labelMove.move(self.x, self.height() - 30)
self.labelMove.adjustSize() # +++
def show_clock(self):
time = QTime.currentTime()
text = time.toString('hh:mm:ss')
self.ui.label_2.setText(text)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
I have this small window code and I want to be able to get the x/y location for the mouse when clicked. I do not see what is the problem in this code, and why it doesn't show me the mouse location
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QGraphicsScene, QMainWindow
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
class Ui_layout_window(QMainWindow):
def setupUi(self, layout_window):
layout_window.setObjectName("layout_window")
layout_window.resize(749, 711)
layout_window.setMouseTracking(True)
self.centralwidget = QtWidgets.QWidget(layout_window)
self.centralwidget.setMouseTracking(True)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setContentsMargins(10, 10, 10, 10)
self.gridLayout.setSpacing(10)
self.gridLayout.setObjectName("gridLayout")
self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 727, 609))
self.scrollAreaWidgetContents.setMouseTracking(True)
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.gridLayout_2 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
self.gridLayout_2.setContentsMargins(5, 5, 5, 5)
self.gridLayout_2.setSpacing(10)
self.gridLayout_2.setObjectName("gridLayout_2")
self.rot_tgt_btn = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
font = QtGui.QFont()
font.setPointSize(10)
self.rot_tgt_btn.setFont(font)
self.rot_tgt_btn.setObjectName("rot_tgt_btn")
self.gridLayout_2.addWidget(self.rot_tgt_btn, 0, 2, 1, 1)
self.scale_spinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
self.scale_spinBox.setFont(font)
self.scale_spinBox.setObjectName("scale_spinBox")
self.scale_spinBox.setRange(10, 5000)
self.scale_spinBox.setValue(1000)
self.gridLayout_2.addWidget(self.scale_spinBox, 0, 5, 1, 1)
self.crop_btn = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
self.crop_btn.setFont(font)
self.crop_btn.setObjectName("crop_btn")
self.gridLayout_2.addWidget(self.crop_btn, 0, 3, 1, 1)
self.graphicsView = QtWidgets.QGraphicsView(self.scrollAreaWidgetContents)
self.graphicsView.setObjectName("graphicsView")
self.gridLayout_2.addWidget(self.graphicsView, 1, 0, 1, 6)
self.ror_lft_btn = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
self.ror_lft_btn.setFont(font)
self.ror_lft_btn.setObjectName("ror_lft_btn")
self.gridLayout_2.addWidget(self.ror_lft_btn, 0, 1, 1, 1)
self.scale_label = QtWidgets.QLabel(self.scrollAreaWidgetContents)
font = QtGui.QFont()
font.setPointSize(10)
self.scale_label.setFont(font)
self.scale_label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.scale_label.setObjectName("scale_label")
self.gridLayout_2.addWidget(self.scale_label, 0, 4, 1, 1)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scene = QGraphicsScene()
self.pixmap = QPixmap("talia.png")
self.pixmap_scl = self.pixmap
self.scene.addPixmap(self.pixmap_scl)
self.graphicsView.setScene(self.scene)
self.gridLayout.addWidget(self.scrollArea, 0, 0, 1, 1)
self.buttonBox = QtWidgets.QDialogButtonBox(self.centralwidget)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 1)
layout_window.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(layout_window)
self.menubar.setGeometry(QtCore.QRect(0, 0, 749, 23))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuImage = QtWidgets.QMenu(self.menubar)
self.menuImage.setObjectName("menuImage")
layout_window.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(layout_window)
self.statusbar.setObjectName("statusbar")
layout_window.setStatusBar(self.statusbar)
self.actionLoad = QtWidgets.QAction(layout_window)
self.actionLoad.setObjectName("actionLoad")
self.actionCrop = QtWidgets.QAction(layout_window)
self.actionCrop.setObjectName("actionCrop")
self.actionZoom = QtWidgets.QAction(layout_window)
self.actionZoom.setObjectName("actionZoom")
self.actionRotate = QtWidgets.QAction(layout_window)
self.actionRotate.setObjectName("actionRotate")
self.actionRotate_Right = QtWidgets.QAction(layout_window)
self.actionRotate_Right.setObjectName("actionRotate_Right")
self.actionRotate_Left = QtWidgets.QAction(layout_window)
self.actionRotate_Left.setObjectName("actionRotate_Left")
self.actionCrop_2 = QtWidgets.QAction(layout_window)
self.actionCrop_2.setObjectName("actionCrop_2")
self.menuFile.addAction(self.actionLoad)
self.menuFile.addAction(self.actionCrop)
self.menuFile.addAction(self.actionZoom)
self.menuFile.addAction(self.actionRotate)
self.menuImage.addAction(self.actionRotate_Right)
self.menuImage.addAction(self.actionRotate_Left)
self.menuImage.addAction(self.actionCrop_2)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuImage.menuAction())
self.statusbar.showMessage("text")
self.retranslateUi(layout_window)
self.buttonBox.accepted.connect(layout_window.close)
self.buttonBox.rejected.connect(layout_window.close)
self.scale_spinBox.editingFinished.connect(self.resizeimg)
QtCore.QMetaObject.connectSlotsByName(layout_window)
def retranslateUi(self, layout_window):
_translate = QtCore.QCoreApplication.translate
layout_window.setWindowTitle(_translate("layout_window", "MainWindow"))
self.rot_tgt_btn.setText(_translate("layout_window", "Rotate Right"))
self.crop_btn.setText(_translate("layout_window", "Crop"))
self.ror_lft_btn.setText(_translate("layout_window", "Rotate Left"))
self.scale_label.setText(_translate("layout_window", "Scale: "))
self.menuFile.setTitle(_translate("layout_window", "File"))
self.menuImage.setTitle(_translate("layout_window", "Image"))
self.actionLoad.setText(_translate("layout_window", "Load"))
self.actionCrop.setText(_translate("layout_window", "Crop"))
self.actionZoom.setText(_translate("layout_window", "Zoom"))
self.actionRotate.setText(_translate("layout_window", "Rotate"))
self.actionRotate_Right.setText(_translate("layout_window", "Rotate Right"))
self.actionRotate_Left.setText(_translate("layout_window", "Rotate Left"))
self.actionCrop_2.setText(_translate("layout_window", "Crop"))
def resizeimg(self):
zm_fct = self.scale_spinBox.value()
pixmap_scl = self.pixmap.scaled(zm_fct, zm_fct, QtCore.Qt.KeepAspectRatio)
print(zm_fct)
self.scene.clear()
self.scene.addPixmap(pixmap_scl)
self.graphicsView.setScene(self.scene)
def mousePressEvent(self, p):
x = p.x()
y = p.y()
print("On Hover", p.pos().x(), p.pos().y())
def mouseMoveEvent(self, e):
x = e.x()
y = e.y()
print("On Hover", e.pos().x(), e.pos().y())
text = "x: {0}, y: {1}".format(x, y)
self.statusbar.showMessage(text)
def mousePressEvent(self, event):
print(event)
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
layout_window = QtWidgets.QMainWindow()
ui = Ui_layout_window()
ui.setupUi(layout_window)
layout_window.show()
sys.exit(app.exec_())
You are defining the function mousePressEvent() twice, and then you never call or bind it to anything.
i have two .ui files that converted to python using pyuic5.
first converted ui file is (LoginWindowUI.py) as below:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_LoginWindow(object):
def setupUi(self, LoginWindow):
LoginWindow.setObjectName("LoginWindow")
LoginWindow.setWindowModality(QtCore.Qt.NonModal)
LoginWindow.setEnabled(True)
LoginWindow.resize(446, 182)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(LoginWindow.sizePolicy().hasHeightForWidth())
LoginWindow.setSizePolicy(sizePolicy)
LoginWindow.setMouseTracking(False)
LoginWindow.setLayoutDirection(QtCore.Qt.RightToLeft)
LoginWindow.setLocale(QtCore.QLocale(QtCore.QLocale.Persian, QtCore.QLocale.Iran))
LoginWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(LoginWindow)
self.centralwidget.setObjectName("centralwidget")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(194, 30, 187, 77))
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.password_ldt = QtWidgets.QLineEdit(self.layoutWidget)
self.password_ldt.setLocale(QtCore.QLocale(QtCore.QLocale.Persian, QtCore.QLocale.Iran))
self.password_ldt.setText("")
self.password_ldt.setEchoMode(QtWidgets.QLineEdit.Password)
self.password_ldt.setCursorPosition(0)
self.password_ldt.setAlignment(QtCore.Qt.AlignCenter)
self.password_ldt.setObjectName("password_ldt")
self.gridLayout.addWidget(self.password_ldt, 1, 1, 1, 1)
self.password_lbl = QtWidgets.QLabel(self.layoutWidget)
self.password_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.password_lbl.setObjectName("password_lbl")
self.gridLayout.addWidget(self.password_lbl, 1, 0, 1, 1)
self.username_lbl = QtWidgets.QLabel(self.layoutWidget)
self.username_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.username_lbl.setObjectName("username_lbl")
self.gridLayout.addWidget(self.username_lbl, 0, 0, 1, 1)
self.username_ldt = QtWidgets.QLineEdit(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.username_ldt.sizePolicy().hasHeightForWidth())
self.username_ldt.setSizePolicy(sizePolicy)
self.username_ldt.setLocale(QtCore.QLocale(QtCore.QLocale.Persian, QtCore.QLocale.Iran))
self.username_ldt.setText("")
self.username_ldt.setEchoMode(QtWidgets.QLineEdit.Normal)
self.username_ldt.setAlignment(QtCore.Qt.AlignCenter)
self.username_ldt.setObjectName("username_ldt")
self.gridLayout.addWidget(self.username_ldt, 0, 1, 1, 1)
self.login_btn = QtWidgets.QPushButton(self.layoutWidget)
self.login_btn.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor))
self.login_btn.setAutoDefault(False)
self.login_btn.setDefault(False)
self.login_btn.setObjectName("login_btn")
self.gridLayout.addWidget(self.login_btn, 2, 1, 1, 1)
self.description_lbl = QtWidgets.QLabel(self.centralwidget)
self.description_lbl.setGeometry(QtCore.QRect(30, 40, 141, 41))
self.description_lbl.setText("")
self.description_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.description_lbl.setWordWrap(True)
self.description_lbl.setObjectName("description_lbl")
LoginWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(LoginWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 446, 21))
self.menubar.setObjectName("menubar")
self.menu = QtWidgets.QMenu(self.menubar)
self.menu.setObjectName("menu")
LoginWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(LoginWindow)
self.statusbar.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
self.statusbar.setObjectName("statusbar")
LoginWindow.setStatusBar(self.statusbar)
self.action_cra = QtWidgets.QAction(LoginWindow)
self.action_cra.setObjectName("action_cra")
self.action_db = QtWidgets.QAction(LoginWindow)
self.action_db.setObjectName("action_db")
self.action_exit = QtWidgets.QAction(LoginWindow)
self.action_exit.setObjectName("action_exit")
self.menu.addAction(self.action_cra)
self.menu.addAction(self.action_db)
self.menu.addSeparator()
self.menu.addAction(self.action_exit)
self.menubar.addAction(self.menu.menuAction())
self.retranslateUi(LoginWindow)
self.action_exit.triggered.connect(LoginWindow.close)
QtCore.QMetaObject.connectSlotsByName(LoginWindow)
LoginWindow.setTabOrder(self.username_ldt, self.password_ldt)
LoginWindow.setTabOrder(self.password_ldt, self.login_btn)
def retranslateUi(self, LoginWindow):
_translate = QtCore.QCoreApplication.translate
self.password_ldt.setToolTip(_translate("LoginWindow", "رمز عبور خود را وارد کنید."))
self.password_lbl.setText(_translate("LoginWindow", " رمز عبور "))
self.username_lbl.setText(_translate("LoginWindow", "نام کاربری"))
self.username_ldt.setToolTip(_translate("LoginWindow", "لطفاً نام کاربری خود را وارد نمایید."))
self.login_btn.setText(_translate("LoginWindow", "ورود"))
self.menu.setTitle(_translate("LoginWindow", "درباره ما"))
self.action_cra.setText(_translate("LoginWindow", "A"))
self.action_db.setText(_translate("LoginWindow", "B"))
self.action_exit.setText(_translate("LoginWindow", "خروج"))
self.action_exit.setStatusTip(_translate("LoginWindow", "خروج"))
self.action_exit.setShortcut(_translate("LoginWindow", "Ctrl+Q"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
LoginWindow = QtWidgets.QMainWindow()
ui = Ui_LoginWindow()
ui.setupUi(LoginWindow)
LoginWindow.show()
sys.exit(app.exec_())
and the second converted .ui file is (MainWindowUI.py) as below:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(452, 432)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.cralogo_lbl = QtWidgets.QLabel(self.centralwidget)
self.cralogo_lbl.setGeometry(QtCore.QRect(90, 30, 171, 161))
self.cralogo_lbl.setText("")
self.cralogo_lbl.setPixmap(QtGui.QPixmap("../../.designer/backup/ICONS/CraLogo.png"))
self.cralogo_lbl.setScaledContents(True)
self.cralogo_lbl.setObjectName("cralogo_lbl")
self.exit_btn = QtWidgets.QPushButton(self.centralwidget)
self.exit_btn.setGeometry(QtCore.QRect(140, 340, 125, 40))
self.exit_btn.setMinimumSize(QtCore.QSize(125, 40))
self.exit_btn.setLayoutDirection(QtCore.Qt.LeftToRight)
self.exit_btn.setCheckable(False)
self.exit_btn.setChecked(False)
self.exit_btn.setObjectName("exit_btn")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(20, 10, 389, 152))
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.mobile_btn = QtWidgets.QPushButton(self.layoutWidget)
self.mobile_btn.setEnabled(False)
self.mobile_btn.setMinimumSize(QtCore.QSize(125, 40))
self.mobile_btn.setLayoutDirection(QtCore.Qt.RightToLeft)
self.mobile_btn.setCheckable(False)
self.mobile_btn.setChecked(False)
self.mobile_btn.setObjectName("mobile_btn")
self.gridLayout.addWidget(self.mobile_btn, 1, 0, 1, 1)
self.dataentry_btn = QtWidgets.QPushButton(self.layoutWidget)
self.dataentry_btn.setMinimumSize(QtCore.QSize(125, 40))
self.dataentry_btn.setLayoutDirection(QtCore.Qt.LeftToRight)
self.dataentry_btn.setCheckable(False)
self.dataentry_btn.setChecked(False)
self.dataentry_btn.setObjectName("dataentry_btn")
self.gridLayout.addWidget(self.dataentry_btn, 0, 2, 1, 1)
self.village_btn = QtWidgets.QPushButton(self.layoutWidget)
self.village_btn.setEnabled(False)
self.village_btn.setMinimumSize(QtCore.QSize(125, 40))
self.village_btn.setLayoutDirection(QtCore.Qt.RightToLeft)
self.village_btn.setCheckable(False)
self.village_btn.setChecked(False)
self.village_btn.setObjectName("village_btn")
self.gridLayout.addWidget(self.village_btn, 1, 1, 1, 1)
self.fix_btn = QtWidgets.QPushButton(self.layoutWidget)
self.fix_btn.setEnabled(False)
self.fix_btn.setMinimumSize(QtCore.QSize(125, 40))
self.fix_btn.setLayoutDirection(QtCore.Qt.RightToLeft)
self.fix_btn.setCheckable(False)
self.fix_btn.setChecked(False)
self.fix_btn.setObjectName("fix_btn")
self.gridLayout.addWidget(self.fix_btn, 0, 0, 1, 1)
self.post_btn = QtWidgets.QPushButton(self.layoutWidget)
self.post_btn.setEnabled(False)
self.post_btn.setMinimumSize(QtCore.QSize(125, 40))
self.post_btn.setLayoutDirection(QtCore.Qt.RightToLeft)
self.post_btn.setCheckable(False)
self.post_btn.setChecked(False)
self.post_btn.setObjectName("post_btn")
self.gridLayout.addWidget(self.post_btn, 2, 0, 1, 1)
self.city_btn = QtWidgets.QPushButton(self.layoutWidget)
self.city_btn.setEnabled(False)
self.city_btn.setMinimumSize(QtCore.QSize(125, 40))
self.city_btn.setLayoutDirection(QtCore.Qt.RightToLeft)
self.city_btn.setCheckable(False)
self.city_btn.setChecked(False)
self.city_btn.setObjectName("city_btn")
self.gridLayout.addWidget(self.city_btn, 0, 1, 1, 1)
self.layoutWidget1 = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget1.setGeometry(QtCore.QRect(20, 190, 389, 134))
self.layoutWidget1.setObjectName("layoutWidget1")
self.gridLayout_2 = QtWidgets.QGridLayout(self.layoutWidget1)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setObjectName("gridLayout_2")
self.rep4_btn = QtWidgets.QPushButton(self.layoutWidget1)
self.rep4_btn.setEnabled(False)
self.rep4_btn.setMinimumSize(QtCore.QSize(125, 40))
self.rep4_btn.setMaximumSize(QtCore.QSize(125, 40))
self.rep4_btn.setCheckable(False)
self.rep4_btn.setObjectName("rep4_btn")
self.gridLayout_2.addWidget(self.rep4_btn, 0, 0, 1, 1)
self.rep1_btn = QtWidgets.QPushButton(self.layoutWidget1)
self.rep1_btn.setEnabled(False)
self.rep1_btn.setMinimumSize(QtCore.QSize(125, 40))
self.rep1_btn.setMaximumSize(QtCore.QSize(125, 40))
self.rep1_btn.setCheckable(False)
self.rep1_btn.setObjectName("rep1_btn")
self.gridLayout_2.addWidget(self.rep1_btn, 0, 1, 1, 1)
self.report_btn = QtWidgets.QPushButton(self.layoutWidget1)
self.report_btn.setMinimumSize(QtCore.QSize(125, 40))
self.report_btn.setMaximumSize(QtCore.QSize(125, 40))
self.report_btn.setCheckable(False)
self.report_btn.setObjectName("report_btn")
self.gridLayout_2.addWidget(self.report_btn, 0, 2, 1, 1)
self.rep5_btn = QtWidgets.QPushButton(self.layoutWidget1)
self.rep5_btn.setEnabled(False)
self.rep5_btn.setMinimumSize(QtCore.QSize(125, 40))
self.rep5_btn.setMaximumSize(QtCore.QSize(125, 40))
self.rep5_btn.setCheckable(False)
self.rep5_btn.setObjectName("rep5_btn")
self.gridLayout_2.addWidget(self.rep5_btn, 1, 0, 1, 1)
self.rep2_btn = QtWidgets.QPushButton(self.layoutWidget1)
self.rep2_btn.setEnabled(False)
self.rep2_btn.setMinimumSize(QtCore.QSize(125, 40))
self.rep2_btn.setMaximumSize(QtCore.QSize(125, 40))
self.rep2_btn.setCheckable(False)
self.rep2_btn.setObjectName("rep2_btn")
self.gridLayout_2.addWidget(self.rep2_btn, 1, 1, 1, 1)
self.rep6_btn = QtWidgets.QPushButton(self.layoutWidget1)
self.rep6_btn.setEnabled(False)
self.rep6_btn.setMinimumSize(QtCore.QSize(125, 40))
self.rep6_btn.setMaximumSize(QtCore.QSize(125, 40))
self.rep6_btn.setCheckable(False)
self.rep6_btn.setObjectName("rep6_btn")
self.gridLayout_2.addWidget(self.rep6_btn, 2, 0, 1, 1)
self.rep3_btn = QtWidgets.QPushButton(self.layoutWidget1)
self.rep3_btn.setEnabled(False)
self.rep3_btn.setMinimumSize(QtCore.QSize(125, 40))
self.rep3_btn.setMaximumSize(QtCore.QSize(125, 40))
self.rep3_btn.setCheckable(False)
self.rep3_btn.setObjectName("rep3_btn")
self.gridLayout_2.addWidget(self.rep3_btn, 2, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 452, 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)
self.exit_btn.clicked.connect(MainWindow.close)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.cralogo_lbl.setStatusTip(_translate("MainWindow", "www.cra.ir"))
self.exit_btn.setText(_translate("MainWindow", "خروج"))
self.mobile_btn.setText(_translate("MainWindow", "4"))
self.dataentry_btn.setText(_translate("MainWindow", "A"))
self.village_btn.setText(_translate("MainWindow", "2"))
self.fix_btn.setText(_translate("MainWindow", "3"))
self.post_btn.setText(_translate("MainWindow", "5"))
self.city_btn.setText(_translate("MainWindow", "1"))
self.rep4_btn.setText(_translate("MainWindow", "4"))
self.rep1_btn.setText(_translate("MainWindow", "1"))
self.report_btn.setText(_translate("MainWindow", "B"))
self.rep5_btn.setText(_translate("MainWindow", "5"))
self.rep2_btn.setText(_translate("MainWindow", "2"))
self.rep6_btn.setText(_translate("MainWindow", "6"))
self.rep3_btn.setText(_translate("MainWindow", "3"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
and my main python file is :
from LoginWindowUI import Ui_LoginWindow
from MainWindowUI import Ui_MainWindow
from PyQt5 import QtCore,QtGui,QtWidgets
import sys
import mysql.connector
open_main_window_flag = False
class Main_Window():
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
self.MWindow = QtWidgets.QMainWindow()
self.ui_MWindow = Ui_MainWindow()
self.ui_MWindow.setupUi(self.MWindow)
self.MWindow.show()
sys.exit(app.exec_())
class login():
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
self.LoginWindow = QtWidgets.QMainWindow()
self.ui_login = Ui_LoginWindow()
self.ui_login.setupUi(self.LoginWindow)
self.ui_login.login_btn.clicked.connect(self.loginform)
self.authentication_flag = False
self.LoginWindow.show()
sys.exit(app.exec_())
def loginform(self):
global open_main_window_flag
db_user = self.ui_login.username_ldt.text()
db_pass = self.ui_login.password_ldt.text()
if(db_user == 'admin' and db_pass=='admin'):
print('Welcome')
self.authentication_flag = True
else:
print('Try Again')
self.authentication_flag = False
if self.authentication_flag:
self.LoginWindow.close()
open_main_window_flag = True
if __name__ == '__main__':
mylogin = login()
if open_main_window_flag:
mymainwindow = Main_Window()
I want that when user enter "admin","admin" in username and password this window colsed and open second ui file .
You have the following errors:
There can only be one object of the QApplication, you are creating one for each window and that is incorrect.
Avoid using global variables, they are considered a bad practice and few cases are necessary. For more information read: Why are global variables evil?
Qt Designer does not offer a widget but a class that serves to fill a widget so PyQt recommend to create a suitable widget class and fill it with that class, for more information read: http://pyqt.sourceforge.net/Docs/PyQt5/designer.html
Going to the point, you can not use a flag because the process is asynchronous, in Qt you work with signals, that's the correct way to inform that there is a change, for example a way to keep the classes separate is to create a signal that indicates that you have logged in, close the window and open the other window.
from LoginWindowUI import Ui_LoginWindow
from MainWindowUI import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
class Main_Window(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Main_Window, self).__init__(parent)
self.setupUi(self)
class LoginWindow(QtWidgets.QMainWindow, Ui_LoginWindow):
logged = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(LoginWindow, self).__init__(parent)
self.setupUi(self)
self.login_btn.clicked.connect(self.authenticate)
#QtCore.pyqtSlot()
def authenticate(self):
db_user = self.username_ldt.text()
db_pass = self.password_ldt.text()
if db_user == 'admin' and db_pass=='admin':
self.logged.emit()
self.close()
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
login = LoginWindow()
w = Main_Window()
login.logged.connect(w.show)
login.show()
sys.exit(app.exec_())
if __name__ == '__main__': main()