Display CV2 Live in QLabel Element - python

I'm currently coding a GUI for a surveillance System I made with OpenCV. I'd like to see the live video input in a QLabel next to the settings box but I'm quite new on the emit/signal/slot topic so I'm a bit overwhelmed by the code order.
The GUI is converted from QtCreator, just to get the Layout right. The buttons don't have any functions yet.
Here's my code so far:
import sys
import cv2
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
#getting the live vid
class Thread(QThread):
changePixmap = pyqtSignal(QImage)
def run(self):
cap1 = cv2.VideoCapture('single.mp4')
while True:
ret, frame = cap1.read()
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
cvt2qt = QImage(rgb_image.data, rgb_image.shape[1], rgb_image.shape[0], QImage.Format_RGB888)
self.changePixmap.emit(cvt2qt) # I don't really understand this yet
class Ui_MainWindow(object):
def setImage(self, image):
self.label.setPixmap(QPixmap.fromImage(image))
#pyqtSlot(QImage) # I'm not sure about this function
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1280, 779)
MainWindow.setMinimumSize(QtCore.QSize(920, 405))
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setMinimumSize(QtCore.QSize(400, 400))
self.centralWidget.setBaseSize(QtCore.QSize(800, 600))
self.centralWidget.setObjectName("centralWidget")
# here is where I want to put the image.
self.label = QtWidgets.QLabel(self.centralWidget)
self.label.setGeometry(QtCore.QRect(10, 10, 881, 671))
self.label.setScaledContents(True)
self.label.setObjectName("label")
th = Thread(self) # Here is, where I struggle
th.changePixmap.connect(self.setImage)
th.start()
MainWindow.setCentralWidget(self.centralWidget)
self.dockWidget = QtWidgets.QDockWidget(MainWindow)
self.dockWidget.setMinimumSize(QtCore.QSize(200, 0))
self.dockWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.dockWidget.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable)
self.dockWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea|QtCore.Qt.RightDockWidgetArea)
self.dockWidget.setObjectName("dockWidget")
self.dockWidgetContents = QtWidgets.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.groupBox = QtWidgets.QGroupBox(self.dockWidgetContents)
self.groupBox.setGeometry(QtCore.QRect(0, 30, 141, 281))
self.groupBox.setMinimumSize(QtCore.QSize(90, 0))
self.groupBox.setObjectName("groupBox")
self.pushButton = QtWidgets.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(10, 20, 121, 32))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_2.setGeometry(QtCore.QRect(10, 50, 121, 32))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_3.setGeometry(QtCore.QRect(10, 80, 121, 32))
self.pushButton_3.setObjectName("pushButton_3")
self.radioButton = QtWidgets.QRadioButton(self.groupBox)
self.radioButton.setGeometry(QtCore.QRect(20, 120, 100, 20))
self.radioButton.setObjectName("radioButton")
self.radioButton_2 = QtWidgets.QRadioButton(self.groupBox)
self.radioButton_2.setGeometry(QtCore.QRect(20, 150, 100, 20))
self.radioButton_2.setObjectName("radioButton_2")
self.radioButton_3 = QtWidgets.QRadioButton(self.groupBox)
self.radioButton_3.setGeometry(QtCore.QRect(20, 180, 100, 20))
self.radioButton_3.setObjectName("radioButton_3")
self.dockWidget.setWidget(self.dockWidgetContents)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "ARCV"))
self.groupBox.setTitle(_translate("MainWindow", "Settings"))
self.pushButton.setText(_translate("MainWindow", "Start Recording"))
self.pushButton_2.setText(_translate("MainWindow", "Stop Recording"))
self.pushButton_3.setText(_translate("MainWindow", "Quit GUI"))
self.radioButton.setText(_translate("MainWindow", "Camera 1"))
self.radioButton_2.setText(_translate("MainWindow", "Camera 2"))
self.radioButton_3.setText(_translate("MainWindow", "Camera 3"))
class Prog(QMainWindow):
def __init__(self):
super().__init__();
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__=='__main__':
Program = QApplication(sys.argv)
MyProg = Prog()
MyProg.show()
sys.exit(Program.exec_())
I hope, you can help me. Thanks.
Aaroknight

QThread waits as a parameter for a parent that must be a QObject, in your case self is an object of the Ui_MainWindow class that does not inherit from QObject causing the problem.
I see that you are implementing a class called Prog, there you must do the logic and not modify the code generated by Qt Designer.
So if we move the logic to that class there should be no problems.
On the other hand the decorator #pyqtSlot must be used in the function that is connected to the signal, you place it in the constructor which does not make sense, it must be on top of setImage().
import sys
import cv2
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1280, 779)
MainWindow.setMinimumSize(QtCore.QSize(920, 405))
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setMinimumSize(QtCore.QSize(400, 400))
self.centralWidget.setBaseSize(QtCore.QSize(800, 600))
self.centralWidget.setObjectName("centralWidget")
# here is where I want to put the image.
self.label = QtWidgets.QLabel(self.centralWidget)
self.label.setGeometry(QtCore.QRect(10, 10, 881, 671))
self.label.setScaledContents(True)
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralWidget)
self.dockWidget = QtWidgets.QDockWidget(MainWindow)
self.dockWidget.setMinimumSize(QtCore.QSize(200, 0))
self.dockWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.dockWidget.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable)
self.dockWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea|QtCore.Qt.RightDockWidgetArea)
self.dockWidget.setObjectName("dockWidget")
self.dockWidgetContents = QtWidgets.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.groupBox = QtWidgets.QGroupBox(self.dockWidgetContents)
self.groupBox.setGeometry(QtCore.QRect(0, 30, 141, 281))
self.groupBox.setMinimumSize(QtCore.QSize(90, 0))
self.groupBox.setObjectName("groupBox")
self.pushButton = QtWidgets.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(10, 20, 121, 32))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_2.setGeometry(QtCore.QRect(10, 50, 121, 32))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_3.setGeometry(QtCore.QRect(10, 80, 121, 32))
self.pushButton_3.setObjectName("pushButton_3")
self.radioButton = QtWidgets.QRadioButton(self.groupBox)
self.radioButton.setGeometry(QtCore.QRect(20, 120, 100, 20))
self.radioButton.setObjectName("radioButton")
self.radioButton_2 = QtWidgets.QRadioButton(self.groupBox)
self.radioButton_2.setGeometry(QtCore.QRect(20, 150, 100, 20))
self.radioButton_2.setObjectName("radioButton_2")
self.radioButton_3 = QtWidgets.QRadioButton(self.groupBox)
self.radioButton_3.setGeometry(QtCore.QRect(20, 180, 100, 20))
self.radioButton_3.setObjectName("radioButton_3")
self.dockWidget.setWidget(self.dockWidgetContents)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "ARCV"))
self.groupBox.setTitle(_translate("MainWindow", "Settings"))
self.pushButton.setText(_translate("MainWindow", "Start Recording"))
self.pushButton_2.setText(_translate("MainWindow", "Stop Recording"))
self.pushButton_3.setText(_translate("MainWindow", "Quit GUI"))
self.radioButton.setText(_translate("MainWindow", "Camera 1"))
self.radioButton_2.setText(_translate("MainWindow", "Camera 2"))
self.radioButton_3.setText(_translate("MainWindow", "Camera 3"))
#getting the live vid
class Thread(QtCore.QThread):
changePixmap = QtCore.pyqtSignal(QtGui.QImage)
def __init__(self, *args, **kwargs):
QtCore.QThread.__init__(self, *args, **kwargs)
self.flag = False
def run(self):
cap1 = cv2.VideoCapture('single.mp4')
self.flag = True
while self.flag:
ret, frame = cap1.read()
if ret:
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
cvt2qt = QtGui.QImage(rgb_image.data, rgb_image.shape[1], rgb_image.shape[0], QtGui.QImage.Format_RGB888)
self.changePixmap.emit(cvt2qt) # I don't really understand this yet
def stop(self):
self.flag = False
class Prog(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.th = Thread(self)
self.th.changePixmap.connect(self.setImage)
self.th.start()
#QtCore.pyqtSlot(QtGui.QImage)
def setImage(self, image):
self.label.setPixmap(QtGui.QPixmap.fromImage(image))
def closeEvent(self, event):
self.th.stop()
self.th.wait()
super().closeEvent(event)
if __name__=='__main__':
Program = QtWidgets.QApplication(sys.argv)
MyProg = Prog()
MyProg.show()
sys.exit(Program.exec_())

Related

Why can't My GUI program built by PyQt5 show?

I refer to the article1 to build my GUI by PyQt5,The difference between the program of the article and mine is the module <img_controller.py>. When I initilize my img_controller instance,I only need the parameter ui(the class I got from Qtdesigner)and my program ,img_controller. will revise the attributes of ui. Initialize the parameters of img_controller.py according to 1 are directed inputted attributes of ui.
When I run the program got from 1, it can work normally; but I run my program, I can't get the mainwindow and the wrong message hints that "AttributeError: 'Img_controller' object has no attribute 'ui'".I don't know where is my problem, because in the function __ init __ of Img_controller(class), I state that "self.ui = ui",anyone can tell me the problem, thank you very much.
The following is my program:
UI.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1085, 857)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(110, 20, 861, 491))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.scrollArea = QtWidgets.QScrollArea(self.verticalLayoutWidget)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
# self.scrollAreaWidgetContents = QtWidgets.QWidget()
# self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 857, 487))
# self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.image_label = QtWidgets.QLabel(self.scrollArea) #此處有更動
self.image_label.setGeometry(QtCore.QRect(10, 10, 841, 471))
self.image_label.setObjectName("image_label")
self.scrollArea.setWidget(self.image_label) #此處有更動
self.verticalLayout.addWidget(self.scrollArea)
self.btn_zoomin = QtWidgets.QPushButton(self.centralwidget)
self.btn_zoomin.setGeometry(QtCore.QRect(330, 530, 75, 23))
self.btn_zoomin.setObjectName("btn_zoomin")
self.btn_zoomout = QtWidgets.QPushButton(self.centralwidget)
self.btn_zoomout.setGeometry(QtCore.QRect(640, 530, 75, 23))
self.btn_zoomout.setObjectName("btn_zoomout")
self.slider = QtWidgets.QSlider(self.centralwidget)
self.slider.setGeometry(QtCore.QRect(440, 530, 160, 22))
self.slider.setOrientation(QtCore.Qt.Horizontal)
self.slider.setObjectName("slider")
self.btn_open = QtWidgets.QPushButton(self.centralwidget)
self.btn_open.setGeometry(QtCore.QRect(140, 530, 75, 23))
self.btn_open.setObjectName("btn_open")
self.label_resolution = QtWidgets.QLabel(self.centralwidget)
self.label_resolution.setGeometry(QtCore.QRect(770, 530, 75, 15))
self.label_resolution.setObjectName("label_resolution")
self.label_filename = QtWidgets.QLabel(self.centralwidget)
self.label_filename.setGeometry(QtCore.QRect(130, 660, 111, 41))
self.label_filename.setObjectName("label_filename")
self.label_img_shape = QtWidgets.QLabel(self.centralwidget)
self.label_img_shape.setGeometry(QtCore.QRect(540, 620, 411, 51))
self.label_img_shape.setObjectName("label_img_shape")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1085, 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.image_label.setText(_translate("MainWindow", "image"))
self.btn_zoomin.setText(_translate("MainWindow", "zoom_in"))
self.btn_zoomout.setText(_translate("MainWindow", "zoom_out"))
self.btn_open.setText(_translate("MainWindow", "open file"))
self.label_resolution.setText(_translate("MainWindow", "TextLabel"))
self.label_filename.setText(_translate("MainWindow", "file_name"))
self.label_img_shape.setText(_translate("MainWindow", "TextLabel"))
img_controller.py
from PyQt5 import QtCore, QtGui
import cv2
from UI import Ui_MainWindow
class Img_controller(object):
def __init__(self, ui:Ui_MainWindow, img_ratio:int = 50):
super(Img_controller, self).__init__()
self.img_path = 'sad.jpg'
self.img_ratio = img_ratio
self.read_img(self.img_path)
self.ui = ui
def read_img(self,img_path):
try:
self.img = cv2.imread(img_path)
self.orig_h, self.orig_w, self.orig_c = self.img.shape
self.img_path = img_path
except:
self.img = cv2.imread(self.img_path)
self.orig_h, self.orig_w, self.orig_c = self.img.shape
bytesPerline = self.orig_h*self.orig_c
self.qimg = QtGui.QImage(self.img, self.orig_w, self.orig_h, bytesPerline, QtGui.QImage.Format_RGB888).rgbSwapped()
self.origin_qpixmap = QtGui.QPixmap.fromImage(self.qimg)
self.img_ratio = 50
self.set_img_ratio()
def set_img_ratio(self):
self.img_ratio = pow(10, (self.img_ratio - 50)/50)
qpixmap_height = self.orig_h * self.img_ratio
self.qpixmap = self.origin_qpixmap.scaledToHeight(qpixmap_height)
#更新UI介面上的顯示
self.__update_img()
self.__update_text_ratio()
self.__update_text_img_shape()
self.__update_text_file_path()
def __update_img(self):
self.ui.image_label.setPixmap(self.qpixmap)
self.ui.image_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
def __update_text_file_path(self):
self.ui.label_filename.setText(f"File path = {self.img_path}")
def __update_text_ratio(self):
self.ui.label_resolution.setText(f"{int(100*self.img_ratio)} %")
def __update_text_img_shape(self):
current_text = f"Current img shape = ({self.qpixmap.width()}, {self.qpixmap.height()})"
origin_text = f"Origin img shape = ({self.origin_width}, {self.origin_height})"
self.ui.label_img_shape.setText(current_text+"\t"+origin_text)
def set_zoom_in(self):
self.img_ratio = max(0, self.img_ratio - 1)
self.set_img_ratio()
def set_zoom_out(self):
self.img_ratio = min(100, self.img_ratio + 1)
self.set_img_ratio()
def set_slider_value(self, value):
self.img_ratio = value
self.set_img_ratio()
controller.py
from PyQt5 import QtCore,QtWidgets,QtGui
from PyQt5.QtWidgets import QMainWindow,QFileDialog
from img_controller import Img_controller
from UI import Ui_MainWindow
class Ui_controller(QMainWindow):
def __init__(self):
super(Ui_controller,self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setup_control()
def setup_control(self):
self.img_controller = Img_controller(ui = self.ui)
self.ui.btn_open.clicked.connect(self.open_file)
self.ui.btn_zoomin.clicked.connect(self.img_controller.set_zoom_in)
self.ui.btn_zoomout.clicked.connect(self.img_controller.set_zoom_out)
self.ui.slider.valueChanged.connect(self.getslidervalue)
def open_file(self):
filename, filetype = QFileDialog.getOpenFileName(self, "Open file", "./") # start path
self.init_new_picture(filename)
def init_new_picture(self, filename):
self.ui.slider.setProperty("value", 50)
self.img_controller.read_img(filename)
def getslidervalue(self):
self.img_controller.set_slider_value(self.ui.slider.value()+1)
What you DIDN'T say was the key piece of information -- the rest of the traceback. Notice that Img_controller.__init__ calls self.read_img, which calls self.set_img_ratio, which calls self.__update_img, which uses self.ui, and that all happens BEFORE you set self.ui. You need to swap the order of that initialization.

How do I save information from one window to be used in another?

I want to make a sport team managing program but I am stuck on this one part. On playertabs.py your supposed to be able to add a new player with a button, this pop up a second window (NewPlayers.py) with the details that needs to be entered. When hitting the add player button the second window (NewPlayers.py) needs to close and all entered information should be saved on the players name that they entered on the playertabs.py window in the form of a list. Multiple players must be added this way.
Main.py codes:
import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QMainWindow
from NewPlayers import Ui_Dialog
#PlayersTab screen
class PlayersTab(QMainWindow):
def __init__(self):
super(PlayersTab, self).__init__()
loadUi("playerstab.ui", self)
self.addnewplayer.clicked.connect(self.openNewPlayers)
#Go to NewPlayers screen
def openNewPlayers(self):
self.window = QtWidgets.QDialog()
self.ui = Ui_Dialog()
self.ui.setupUi(self.window)
self.window.show()
#Go to PlayerTab screen
def gotoPlayersTab(self):
widget.setCurrentIndex(widget.currentIndex() + 1)
# main
app = QApplication(sys.argv)
widget = QtWidgets.QStackedWidget()
playerstab = PlayersTab()
widget.addWidget(playerstab)
widget.setFixedHeight(480)
widget.setFixedWidth(640)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")
playertab.py code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.addnewplayer = QtWidgets.QPushButton(self.centralwidget)
self.addnewplayer.setGeometry(QtCore.QRect(450, 50, 181, 31))
self.addnewplayer.setObjectName("addnewplayer")
self.playerlist = QtWidgets.QListWidget(self.centralwidget)
self.playerlist.setGeometry(QtCore.QRect(0, 90, 630, 380))
self.playerlist.setObjectName("playerlist")
self.matches = QtWidgets.QPushButton(self.centralwidget)
self.matches.setGeometry(QtCore.QRect(10, 50, 181, 31))
self.matches.setObjectName("matches")
self.searchplayer = QtWidgets.QLineEdit(self.centralwidget)
self.searchplayer.setGeometry(QtCore.QRect(10, 10, 621, 31))
self.searchplayer.setObjectName("searchplayer")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.addnewplayer.setText(_translate("MainWindow", "Add new player"))
self.matches.setText(_translate("MainWindow", "Matches"))
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_())
NewPlayer.py code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(640, 480)
self.addPhoto = QtWidgets.QPushButton(Dialog)
self.addPhoto.setGeometry(QtCore.QRect(10, 410, 100, 50))
font = QtGui.QFont()
font.setPointSize(11)
self.addPhoto.setFont(font)
self.addPhoto.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
self.addPhoto.setObjectName("addPhoto")
self.p_name = QtWidgets.QLineEdit(Dialog)
self.p_name.setEnabled(True)
self.p_name.setGeometry(QtCore.QRect(400, 36, 200, 44))
self.p_name.setObjectName("p_name")
self.p_prfname = QtWidgets.QLineEdit(Dialog)
self.p_prfname.setGeometry(QtCore.QRect(400, 80, 200, 44))
self.p_prfname.setObjectName("p_prfname")
self.p_height = QtWidgets.QLineEdit(Dialog)
self.p_height.setGeometry(QtCore.QRect(400, 168, 200, 44))
self.p_height.setObjectName("p_height")
self.p_nr = QtWidgets.QLineEdit(Dialog)
self.p_nr.setGeometry(QtCore.QRect(400, 212, 200, 44))
self.p_nr.setObjectName("p_nr")
self.p_placeob = QtWidgets.QLineEdit(Dialog)
self.p_placeob.setGeometry(QtCore.QRect(400, 256, 200, 44))
self.p_placeob.setObjectName("p_placeob")
self.p_weight = QtWidgets.QLineEdit(Dialog)
self.p_weight.setGeometry(QtCore.QRect(400, 300, 200, 44))
self.p_weight.setObjectName("p_weight")
self.back = QtWidgets.QPushButton(Dialog)
self.back.setGeometry(QtCore.QRect(280, 410, 100, 50))
font = QtGui.QFont()
font.setPointSize(11)
self.back.setFont(font)
self.back.setObjectName("back")
#addplayer Button
self.addPlayer = QtWidgets.QPushButton(Dialog, clicked=lambda: self.savePlayer())
self.addPlayer.setGeometry(QtCore.QRect(520, 410, 100, 50))
font = QtGui.QFont()
font.setPointSize(11)
self.addPlayer.setFont(font)
self.addPlayer.setObjectName("addPlayer")
self.p_dob = QtWidgets.QLineEdit(Dialog)
self.p_dob.setGeometry(QtCore.QRect(400, 124, 200, 44))
self.p_dob.setObjectName("p_dob")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def savePlayer(self):
# blank list to hold player info
playerInfo = []
# loop through data and pull out each info
playerInfo.append(self.p_name)
playerInfo.append(self.p_prfname)
playerInfo.append(self.p_dob)
playerInfo.append(self.p_height)
playerInfo.append(self.p_nr)
playerInfo.append(self.p_placeob)
playerInfo.append(self.p_weight)
p_name = self.p_name.text()
print(p_name)
# close window
# NewPlayers.close()
from playerstab import Ui_MainWindow
# self.ui.playerlist.addItem(player)
from Main import PlayersTab
from Main import widget
playerstab = PlayersTab()
widget.addWidget(playerstab)
widget.setCurrentIndex(widget.currentIndex()+1)
#add player
player = p_name
playerstab.playerlist.addItem(player)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "CourseWork"))
self.addPhoto.setText(_translate("Dialog", "Add Photo"))
self.p_name.setText(_translate("Dialog", "Full name & Surname"))
self.p_prfname.setText(_translate("Dialog", "Preferred Name"))
self.p_height.setText(_translate("Dialog", "Height"))
self.p_nr.setText(_translate("Dialog", "Cellphone number"))
self.p_placeob.setText(_translate("Dialog", "Place of Birth"))
self.p_weight.setText(_translate("Dialog", "Weight"))
self.back.setText(_translate("Dialog", "Back"))
self.addPlayer.setText(_translate("Dialog", "Add Player"))
self.p_dob.setText(_translate("Dialog", "Date of Birth (DD/MM/YY)"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())

How to pass variable through different windows in PyQt5?

I have two windows, first window is 'FirstWindow' and second is 'Calendar'. first window has one push button (pbSelectDate) and one label (lbDate). calendar window has calendar (CalendarBox) and one push button (pbSelect).
when i click select (pbSelectDate) from first window, calendar window pops up. I select the date and press select button (pbSelect) in the calendar window. i want to print the selected date to the label (lbDate) in the first window.
thanks in advance. :)
this is the first window script.
from PyQt5 import QtCore, QtGui, QtWidgets
from Calendar import Ui_CalendarWindow
class Ui_FirstWindow(object):
def Open_Calendar(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_CalendarWindow()
self.ui.setupUi(self.window)
self.window.show()
def setupUi(self, FirstWindow):
FirstWindow.setObjectName("FirstWindow")
FirstWindow.resize(654, 242)
self.centralwidget = QtWidgets.QWidget(FirstWindow)
self.centralwidget.setObjectName("centralwidget")
self.lbDate = QtWidgets.QLabel(self.centralwidget)
self.lbDate.setGeometry(QtCore.QRect(330, 70, 281, 131))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.lbDate.setFont(font)
self.lbDate.setLayoutDirection(QtCore.Qt.LeftToRight)
self.lbDate.setObjectName("lbDate")
self.pbSelectDate = QtWidgets.QPushButton(self.centralwidget)
self.pbSelectDate.setGeometry(QtCore.QRect(80, 100, 191, 61))
self.pbSelectDate.setObjectName("pbSelectDate")
self.pbSelectDate.clicked.connect(self.Open_Calendar)
FirstWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(FirstWindow)
self.statusbar.setObjectName("statusbar")
FirstWindow.setStatusBar(self.statusbar)
self.retranslateUi(FirstWindow)
QtCore.QMetaObject.connectSlotsByName(FirstWindow)
def retranslateUi(self, FirstWindow):
_translate = QtCore.QCoreApplication.translate
FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
self.lbDate.setText(_translate("FirstWindow", "Sep"))
self.pbSelectDate.setText(_translate("FirstWindow", "Select Date"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
FirstWindow = QtWidgets.QMainWindow()
ui = Ui_FirstWindow()
ui.setupUi(FirstWindow)
FirstWindow.show()
sys.exit(app.exec_())
this is the Calendar window script..
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CalendarWindow(object):
def PickedDate(self,var):
self.selecteddate = self.CalendarBox.selectedDate()
#print(self.selecteddate.toString('MMM')+'-'+self.selecteddate.toString('yyyy'))
def setupUi(self, CalendarWindow):
CalendarWindow.setObjectName("CalendarWindow")
CalendarWindow.resize(512, 458)
self.centralwidget = QtWidgets.QWidget(CalendarWindow)
self.centralwidget.setObjectName("centralwidget")
self.CalendarBox = QtWidgets.QCalendarWidget(self.centralwidget)
self.CalendarBox.setGeometry(QtCore.QRect(20, 20, 464, 289))
self.CalendarBox.setObjectName("CalendarBox")
self.pbSelect = QtWidgets.QPushButton(self.centralwidget)
self.pbSelect.setGeometry(QtCore.QRect(160, 330, 181, 60))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.pbSelect.setFont(font)
self.pbSelect.setObjectName("pbSelect")
self.pbSelect.clicked.connect(self.PickedDate)
CalendarWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(CalendarWindow)
self.statusbar.setObjectName("statusbar")
CalendarWindow.setStatusBar(self.statusbar)
self.retranslateUi(CalendarWindow)
QtCore.QMetaObject.connectSlotsByName(CalendarWindow)
def retranslateUi(self, CalendarWindow):
_translate = QtCore.QCoreApplication.translate
CalendarWindow.setWindowTitle(_translate("CalendarWindow", "MainWindow"))
self.pbSelect.setText(_translate("CalendarWindow", "Select"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
CalendarWindow = QtWidgets.QMainWindow()
ui = Ui_CalendarWindow()
ui.setupUi(CalendarWindow)
CalendarWindow.show()
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.
QLabel.setText(const QString )
Setting the text clears any previous content.
from PyQt5 import QtCore, QtGui, QtWidgets
#from Calendar import Ui_CalendarWindow
class Ui_CalendarWindow(object):
def setupUi(self, CalendarWindow):
CalendarWindow.setObjectName("CalendarWindow")
CalendarWindow.resize(512, 458)
self.centralwidget = QtWidgets.QWidget(CalendarWindow)
self.centralwidget.setObjectName("centralwidget")
self.CalendarBox = QtWidgets.QCalendarWidget(self.centralwidget)
self.CalendarBox.setGeometry(QtCore.QRect(20, 20, 464, 289))
self.CalendarBox.setObjectName("CalendarBox")
self.pbSelect = QtWidgets.QPushButton(self.centralwidget)
self.pbSelect.setGeometry(QtCore.QRect(160, 330, 181, 60))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.pbSelect.setFont(font)
self.pbSelect.setObjectName("pbSelect")
# self.pbSelect.clicked.connect(self.PickedDate)
CalendarWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(CalendarWindow)
self.statusbar.setObjectName("statusbar")
CalendarWindow.setStatusBar(self.statusbar)
self.retranslateUi(CalendarWindow)
QtCore.QMetaObject.connectSlotsByName(CalendarWindow)
def retranslateUi(self, CalendarWindow):
_translate = QtCore.QCoreApplication.translate
CalendarWindow.setWindowTitle(_translate("CalendarWindow", "MainWindow"))
self.pbSelect.setText(_translate("CalendarWindow", "Select"))
class Ui_FirstWindow(object):
def setupUi(self, FirstWindow):
FirstWindow.setObjectName("FirstWindow")
FirstWindow.resize(654, 242)
self.centralwidget = QtWidgets.QWidget(FirstWindow)
self.centralwidget.setObjectName("centralwidget")
self.lbDate = QtWidgets.QLabel(self.centralwidget)
self.lbDate.setGeometry(QtCore.QRect(330, 70, 281, 131))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.lbDate.setFont(font)
self.lbDate.setLayoutDirection(QtCore.Qt.LeftToRight)
self.lbDate.setObjectName("lbDate")
self.pbSelectDate = QtWidgets.QPushButton(self.centralwidget)
self.pbSelectDate.setGeometry(QtCore.QRect(80, 100, 191, 61))
self.pbSelectDate.setObjectName("pbSelectDate")
# self.pbSelectDate.clicked.connect(self.Open_Calendar)
FirstWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(FirstWindow)
self.statusbar.setObjectName("statusbar")
FirstWindow.setStatusBar(self.statusbar)
self.retranslateUi(FirstWindow)
QtCore.QMetaObject.connectSlotsByName(FirstWindow)
def retranslateUi(self, FirstWindow):
_translate = QtCore.QCoreApplication.translate
FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
self.lbDate.setText(_translate("FirstWindow", "Sep"))
self.pbSelectDate.setText(_translate("FirstWindow", "Select Date"))
class CalendarWindow(QtWidgets.QMainWindow, Ui_CalendarWindow): # +
def __init__(self):
super(CalendarWindow, self).__init__()
self.setupUi(self)
class FirstWindow(QtWidgets.QMainWindow, Ui_FirstWindow): # +
def __init__(self):
super(FirstWindow, self).__init__()
self.setupUi(self)
self.pbSelectDate.clicked.connect(self.Open_Calendar)
def Open_Calendar(self):
self.window = CalendarWindow()
self.window.setupUi(self.window)
self.window.show()
self.window.pbSelect.clicked.connect(self.PickedDate)
def PickedDate(self): # , var
self.selecteddate = self.window.CalendarBox.selectedDate()
# print(self.selecteddate.toString('MMM')+'-'+self.selecteddate.toString('yyyy'))
self.lbDate.setText(self.selecteddate.toString('ddd-MMM-yyyy')) # <---
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = FirstWindow()
w.show()
sys.exit(app.exec_())

Window closes after going to another window then coming back

I am trying to go from window to window and back and forward.
I have tried using while True: and cannot seem to get it to work. It just prints HOME a million times and crashes the window.
from PyQt5 import QtCore, QtGui, QtWidgets
import IMAGE_rc
import sys
from GUIWINDOW1 import *
import time
class Ui_MainWindow(object):
def setup(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setEnabled(True)
MainWindow.resize(800, 480)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(800, 480))
MainWindow.setMaximumSize(QtCore.QSize(800, 480))
MainWindow.setMouseTracking(False)
MainWindow.setStyleSheet("background-color: rgb(170, 255, 127);")
MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setMinimumSize(QtCore.QSize(800, 480))
self.centralwidget.setMaximumSize(QtCore.QSize(800, 480))
self.centralwidget.setObjectName("centralwidget")
self.TOUCH1 = QtWidgets.QPushButton(self.centralwidget)
self.TOUCH1.setGeometry(QtCore.QRect(70, 10, 662, 200))
self.TOUCH1.setStyleSheet("border-image: url(/PROGRAMMING/QT DESIGNER/GUIIMAGES/LOGO.png);")
self.TOUCH1.setText("")
self.TOUCH1.setObjectName("TOUCH1")
self.TOUCH2 = QtWidgets.QPushButton(self.centralwidget)
self.TOUCH2.setGeometry(QtCore.QRect(210, 220, 360, 200))
self.TOUCH2.setStyleSheet("border-image: url(/PROGRAMMING/QT DESIGNER/GUIIMAGES/1200px-Florida_Atlantic_Owls_logo.svg.png);\n"
"background-color: rgb(170, 255, 127);")
self.TOUCH2.setText("")
self.TOUCH2.setObjectName("TOUCH2")
self.TOUCH4 = QtWidgets.QPushButton(self.centralwidget)
self.TOUCH4.setGeometry(QtCore.QRect(0, 0, 801, 481))
self.TOUCH4.setStyleSheet("")
self.TOUCH4.setObjectName("TOUCH4")
self.TOUCH3 = QtWidgets.QPushButton(self.centralwidget)
self.TOUCH3.setGeometry(QtCore.QRect(70, 430, 611, 41))
font = QtGui.QFont()
font.setPointSize(16)
self.TOUCH3.setFont(font)
self.TOUCH3.setStyleSheet("")
self.TOUCH3.setObjectName("TOUCH3")
self.TOUCH4.raise_()
self.TOUCH1.raise_()
self.TOUCH2.raise_()
self.TOUCH3.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.TOUCH1.clicked.connect(self.BEGIN)
self.TOUCH2.clicked.connect(self.BEGIN)
self.TOUCH3.clicked.connect(self.BEGIN)
self.TOUCH4.clicked.connect(self.BEGIN)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.TOUCH4.setText(_translate("MainWindow", "PushButton"))
self.TOUCH3.setText(_translate("MainWindow", "TAP ANYWHERE TO BEGIN"))
def BEGIN(self):
print("HOME")
self.WINDOW1=QtWidgets.QMainWindow()
self.ui = Ui_WINDOW1()
self.ui.setup(self.WINDOW1)
self.WINDOW1.showFullScreen()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setup(MainWindow)
MainWindow.showFullScreen()
sys.exit(app.exec_())
Window closes when i go back and forward from MainWindow to WINDOW1 and try to go back to WINDOW1

Display a down arrow in a widget

I want to display a downward facing arrow (or any shape really) in QT designer between two lineEdits. This seems simple, but I can't seem to find an answer. I have code below that shows what I am trying to do. Any help is greatly appreciated!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPainter, QBrush, QPen
from PyQt5.QtCore import Qt
class Ui_Frame(object):
def setupUi(self, Frame):
Frame.setObjectName("Frame")
Frame.resize(472, 408)
Frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
Frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.verticalLayout = QtWidgets.QVBoxLayout(Frame)
self.verticalLayout.setObjectName("verticalLayout")
self.lineEdit = QtWidgets.QLineEdit(Frame)
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.frame = QtWidgets.QFrame(Frame)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.frame_3 = QtWidgets.QFrame(self.frame)
self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_3.setObjectName("frame_3")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_3)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.label_2 = QtWidgets.QLabel(self.frame_3)
self.label_2.setObjectName("label_2")
self.horizontalLayout_2.addWidget(self.label_2)
self.lineEdit_4 = QtWidgets.QLineEdit(self.frame_3)
self.lineEdit_4.setObjectName("lineEdit_4")
self.horizontalLayout_2.addWidget(self.lineEdit_4)
self.verticalLayout_2.addWidget(self.frame_3)
# I would like to paint a shape on this frame (frame_paint) using method paintEvent
self.frame_paint = QtWidgets.QFrame(self.frame)
self.frame_paint.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_paint.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_paint.setObjectName("frame_paint")
self.verticalLayout_2.addWidget(self.frame_paint)
self.frame_2 = QtWidgets.QFrame(self.frame)
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame_2)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(self.frame_2)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.lineEdit_3 = QtWidgets.QLineEdit(self.frame_2)
self.lineEdit_3.setObjectName("lineEdit_3")
self.horizontalLayout.addWidget(self.lineEdit_3)
self.verticalLayout_2.addWidget(self.frame_2)
self.verticalLayout.addWidget(self.frame)
self.retranslateUi(Frame)
QtCore.QMetaObject.connectSlotsByName(Frame)
def retranslateUi(self, Frame):
_translate = QtCore.QCoreApplication.translate
Frame.setWindowTitle(_translate("Frame", "Frame"))
self.lineEdit.setText(_translate("Frame", "(Name of research project)"))
self.label_2.setText(_translate("Frame", "Level 1:"))
self.label.setText(_translate("Frame", "Level 2:"))
### I want this paintEvent to go to the self.frame_paint
def paintEvent(self, e):
painter = QPainter(self)
painter.setPen(QPen(Qt.black, 10, Qt.SolidLine))
painter.drawRect(100, 15, 400, 200)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Frame = QtWidgets.QFrame()
ui = Ui_Frame()
ui.setupUi(Frame)
Frame.show()
sys.exit(app.exec_())
After some time, I figured it out. I was missing the whole thing about having two py files and implementing painting on a scene. Here is my code that works.
class MainWindow_RUA(QtWidgets.QMainWindow, Ui_MainWindow_RUA):
def __init__(self, parent=None):
super(MainWindow_RUA, self).__init__(parent)
self.setupUi(self)
scene = Painter()
self.graphicsView.setScene(scene)
class Painter(QtWidgets.QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.black))
pen.setWidth(2)
brush = QtGui.QBrush(pen.color().darker(150))
self.addLine(100, 200, 100, 100, pen)
self.addLine(85, 175, 100, 200, pen)
self.addLine(100, 200, 115, 175, pen)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
application = MainWindow_RUA()
application.show()
sys.exit(app.exec_())

Categories