So, I want to close the function on_click_on_start which has while loop in it. And, dont want to close the window after hitting the stop button. Right now, I was using sys.exit() which crashed the program for some reason but, when I used only quit() it was closing the entire app. I am doing this on pyQt5. I am noob to GUI so please help me out. This is extra text which I have added so that I can post the question. Please ignore this.
import res1
import res
from PyQt5 import QtCore, QtGui, QtWidgets
import os
import pyaudio
import numpy as np
import pyautogui
import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setEnabled(True)
MainWindow.resize(800, 600)
MainWindow.setMaximumSize(QtCore.QSize(800, 600))
font = QtGui.QFont()
font.setFamily("Californian FB")
font.setPointSize(14)
MainWindow.setFont(font)
MainWindow.setMouseTracking(True)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(
"../../../../Pictures/ugo_trans.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setAutoFillBackground(True)
MainWindow.setStyleSheet("")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setAutoFillBackground(False)
self.centralwidget.setStyleSheet("background-color: rgb(255, 0, 0);")
self.centralwidget.setObjectName("centralwidget")
self.Backgroundimage = QtWidgets.QLabel(self.centralwidget)
self.Backgroundimage.setEnabled(True)
self.Backgroundimage.setGeometry(QtCore.QRect(9, 9, 782, 582))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.Backgroundimage.sizePolicy().hasHeightForWidth())
self.Backgroundimage.setSizePolicy(sizePolicy)
self.Backgroundimage.setMaximumSize(QtCore.QSize(800, 600))
self.Backgroundimage.setStyleSheet("")
self.Backgroundimage.setText("")
self.Backgroundimage.setPixmap(
QtGui.QPixmap(":/newPrefix/Untitled-1.png"))
self.Backgroundimage.setScaledContents(True)
self.Backgroundimage.setObjectName("Backgroundimage")
self.Start = QtWidgets.QPushButton(self.centralwidget)
self.Start.setGeometry(QtCore.QRect(60, 240, 221, 111))
font = QtGui.QFont()
font.setPointSize(16)
self.Start.setFont(font)
self.Start.setStyleSheet("background-color: rgb(0, 0, 0);\n"
"color: rgb(255, 255, 255);")
self.Start.setObjectName("Start")
self.Stop = QtWidgets.QPushButton(self.centralwidget)
self.Stop.setGeometry(QtCore.QRect(510, 240, 221, 111))
font = QtGui.QFont()
font.setPointSize(16)
self.Stop.setFont(font)
self.Stop.setStyleSheet("background-color: rgb(0, 0, 0);\n"
"color: rgb(255, 255, 255);")
self.Stop.setObjectName("Stop")
self.Title = QtWidgets.QLabel(self.centralwidget)
self.Title.setGeometry(QtCore.QRect(210, 70, 361, 61))
font = QtGui.QFont()
font.setPointSize(48)
self.Title.setFont(font)
self.Title.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgb(0, 0, 0, 60);")
self.Title.setObjectName("Title")
MainWindow.setCentralWidget(self.centralwidget)
self.Start.clicked.connect(self.on_click_on_start) # button pressed on start
self.Stop.clicked.connect(self.on_click_on_stop) # button pressed on stop and it only stops the on_click_on_start
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def on_click_on_start(self):
CHUNK = 2**11
RATE = 48016
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True,
frames_per_buffer=CHUNK)
start = time.time()
while 1:
data = np.fromstring(stream.read(CHUNK), dtype=np.int16)
peak = np.average(np.abs(data))*2
bars = 100*peak/2**16
if bars > 1:
pyautogui.keyDown("NUM0")
start = time.time()
print('down')
else:
pyautogui.keyUp("NUM0")
print('up')
if time.time() - start > 5:
stream.stop_stream()
stream.close()
p.terminate()
break
def on_click_on_stop(self):
# Help me with this function
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Talk to Mute"))
self.Start.setText(_translate("MainWindow", "Start"))
self.Stop.setText(_translate("MainWindow", "Stop"))
self.Title.setText(_translate("MainWindow", "Talk to Mute"))
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_())
Generally using variables is easiest way to manage status. You can use variable for update running status.
running_status = false
Use like
self.running_status = true
in on_click_on_start.
Use
self.running_status = false
in on_click_on_stop. So now you can call your function if running_status is true.
Related
This is my code. The code in email_compare() is my problem. I want it to take the input from the email box and compare it to the emails in my Sqlite database using a linear search. The problem is that though the input is exactly the same it won't output that it is correct. I have had to delete certain parts of my code due to having more code than writing so if it is required I will right back to say what I have deleted. Also I am not sure if you can turn Sqlite records into variables that can actually be compared so if there is another way of doing this then I would greatly appreciate being told how to do it in that method instead of what I am trying to do now.
from PyQt6 import QtCore, QtGui, QtWidgets
import sqlite3
from SIGNUP import Ui_MainWindow
class Ui_Dialog(object):
def openWindow(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.window)
Dialog.close()
self.window.show()
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(480, 620)
Dialog.setStyleSheet("background: rgb(64, 64, 64)")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(210, 60, 200, 50))
self.label.setStyleSheet("color:rgb(255, 255, 255);\n"
"font-size: 28pt;")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(60, 150, 91, 41))
self.label_2.setStyleSheet("font: 23pt; color: rgb(255, 0, 0)")
self.label_2.setObjectName("label_2")
self.email = QtWidgets.QLineEdit(Dialog)
self.email.setGeometry(QtCore.QRect(60, 190, 251, 41))
self.email.setStyleSheet("color: rgb(255, 255, 255)")
self.email.setObjectName("email")
self.label_3 = QtWidgets.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(60, 260, 101, 41))
self.label_3.setStyleSheet("font: 23pt; color: rgb(255, 0, 0)")
self.label_3.setObjectName("label_3")
self.password = QtWidgets.QLineEdit(Dialog)
self.password.setGeometry(QtCore.QRect(60, 300, 251, 41))
self.password.setStyleSheet("color: rgb(255, 255, 255)")
self.password.setText("")
self.password.setObjectName("password")
self.loginbutton = QtWidgets.QPushButton(Dialog)
self.loginbutton.setGeometry(QtCore.QRect(330, 390, 100, 32))
self.loginbutton.setStyleSheet("color: rgb(255, 0, 0)")
self.loginbutton.setObjectName("loginbutton")
self.loginbutton_2 = QtWidgets.QPushButton(Dialog)
self.loginbutton_2.setGeometry(QtCore.QRect(50, 390, 100, 32))
self.loginbutton_2.setStyleSheet("background-color: rgb(0, 255, 212);")
self.loginbutton_2.setObjectName("loginbutton_2")
self.loginbutton_2.clicked.connect(self.openWindow)
self.loginbutton.clicked.connect(self.show_password)
self.loginbutton.clicked.connect(self.email_compare)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Login"))
self.label_2.setText(_translate("Dialog", "Email"))
self.label_3.setText(_translate("Dialog", "Password"))
self.loginbutton.setText(_translate("Dialog", "Login!"))
self.loginbutton_2.setText(_translate("Dialog", "Sign up!"))
# this is my problem
def email_compare(self):
count = 0
check = self.email.text()
check = "('"+check+"',)"
conn = sqlite3.connect("U+P.db")
c = conn.cursor()
c.execute("SELECT email FROM Details")
compare = c.fetchall()
print(compare)
print(check)
right = False
while count < len(compare) and right == False:
print(compare[count])
if compare[count] == check:
print("Correct email")
right = True
else:
count = count + 1
conn.close()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec())
I have 2 windows, MainScreen and AddFW.
Whenever I go from MainScreen -> AddFW, it works (the MainScreen hides and the AddFW appears).
But when I try going back from AddFW to MainScreen, the window crashes and I get an error: "NameError: name 'AddFW' is not defined".
What am I doing wrong?
MainScreen.py
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLineEdit, QPushButton
from PyQt5 import *
from PyQt5 import QtGui
from AddFW import *
import pyodbc
server = '**'
database = '**'
username = '**'
password = '**'
conn = pyodbc.connect('DRIVER={**};'
'SERVER=' + server + ';'
'DATABASE=' + database + ';'
'UID=' + username + ';'
'PWD=' + password)
class Ui_MainWindow(object):
def OpenAddFW(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_AddFW()
self.ui.setupUi(self.window)
self.window.show()
MainWindow.hide()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1000, 600)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 0, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
MainWindow.setPalette(palette)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(410, 40, 201, 41))
font = QtGui.QFont()
font.setFamily("Imprint MT Shadow")
font.setPointSize(27)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
self.label.setFont(font)
self.label.setObjectName("label")
self.InsertResultsBtn = QtWidgets.QPushButton(self.centralwidget)
self.InsertResultsBtn.setGeometry(QtCore.QRect(58, 226, 160, 130))
font = QtGui.QFont()
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.InsertResultsBtn.setFont(font)
self.InsertResultsBtn.setObjectName("InsertResultsBtn")
self.SearchResultsBtn = QtWidgets.QPushButton(self.centralwidget)
self.SearchResultsBtn.setGeometry(QtCore.QRect(300, 226, 160, 130))
font = QtGui.QFont()
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.SearchResultsBtn.setFont(font)
self.SearchResultsBtn.setObjectName("SearchResultsBtn")
self.CompareResultsBtn = QtWidgets.QPushButton(self.centralwidget)
self.CompareResultsBtn.setGeometry(QtCore.QRect(541, 226, 160, 130))
font = QtGui.QFont()
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.CompareResultsBtn.setFont(font)
self.CompareResultsBtn.setObjectName("CompareResultsBtn")
self.AddFWBtn = QtWidgets.QPushButton(self.centralwidget)
self.AddFWBtn.setGeometry(QtCore.QRect(783, 226, 160, 130))
font = QtGui.QFont()
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.AddFWBtn.setFont(font)
self.AddFWBtn.setObjectName("AddFWBtn")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setEnabled(True)
self.label_2.setGeometry(QtCore.QRect(420, 540, 181, 16))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 0, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
self.label_2.setPalette(palette)
self.label_2.setObjectName("label_2")
MainWindow.setCentralWidget(self.centralwidget)
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", "TestTrack"))
self.InsertResultsBtn.setText(_translate("MainWindow", "Insert Results"))
self.SearchResultsBtn.setText(_translate("MainWindow", "Search Results"))
self.CompareResultsBtn.setText(_translate("MainWindow", "Compare Results"))
self.AddFWBtn.setText(_translate("MainWindow", "Add Firmware"))
self.label_2.setText(_translate("MainWindow", "George Hanna & Nadav Benun"))
self.AddFWBtn.clicked.connect(self.OpenAddFW)
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_())
AddFW
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLineEdit
from PyQt5 import *
from PyQt5 import QtGui
from MainScreen import *
import pyodbc
server = '**'
database = '**'
username = '**'
password = '**'
conn = pyodbc.connect('DRIVER={**};'
'SERVER=' + server + ';'
'DATABASE=' + database + ';'
'UID=' + username + ';'
'PWD=' + password)
def create(conn2, AddToDataBase):
cursor = conn2.cursor()
cursor.execute('insert into dbo.Firmware(Firmware) values(?);', AddToDataBase)
conn2.commit()
print('Added!')
class Ui_AddFW(object):
def AddFWFunc(self):
create(conn, self.FirmwareInsert.text())
def BackToMain(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.window)
self.window.show()
AddFW.hide()
def setupUi(self, AddFW):
AddFW.setObjectName("AddFW")
AddFW.resize(1000, 600)
self.centralwidget = QtWidgets.QWidget(AddFW)
self.centralwidget.setObjectName("centralwidget")
self.AddFWButton = QtWidgets.QPushButton(self.centralwidget)
self.AddFWButton.setGeometry(QtCore.QRect(470, 260, 121, 28))
self.AddFWButton.setObjectName("AddFWButton")
self.Back = QtWidgets.QPushButton(self.centralwidget)
self.Back.setGeometry(QtCore.QRect(40, 40, 51, 28))
self.Back.setObjectName("Back")
self.FirmwareLabel = QtWidgets.QLabel(self.centralwidget)
self.FirmwareLabel.setGeometry(QtCore.QRect(320, 170, 60, 16))
self.FirmwareLabel.setObjectName("FirmwareLabel")
self.Title = QtWidgets.QLabel(self.centralwidget)
self.Title.setGeometry(QtCore.QRect(370, 50, 321, 16))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.Title.setFont(font)
self.Title.setObjectName("Title")
self.FirmwareInsert = QtWidgets.QLineEdit(self.centralwidget)
self.FirmwareInsert.setGeometry(QtCore.QRect(400, 160, 281, 31))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.FirmwareInsert.sizePolicy().hasHeightForWidth())
self.FirmwareInsert.setSizePolicy(sizePolicy)
self.FirmwareInsert.setObjectName("FirmwareInsert")
AddFW.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(AddFW)
self.statusbar.setObjectName("statusbar")
AddFW.setStatusBar(self.statusbar)
self.retranslateUi(AddFW)
QtCore.QMetaObject.connectSlotsByName(AddFW)
def retranslateUi(self, AddFW):
_translate = QtCore.QCoreApplication.translate
AddFW.setWindowTitle(_translate("AddFW", "MainWindow"))
self.AddFWButton.setText(_translate("AddFW", "Insert to DataBase"))
self.Back.setText(_translate("AddFW", "Back"))
self.FirmwareLabel.setText(_translate("AddFW", "Firmware:"))
self.Title.setText(_translate("AddFW", "Add Firmware to the DataBase"))
self.AddFWButton.clicked.connect(self.AddFWFunc)
self.Back.clicked.connect(self.BackToMain)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
AddFW = QtWidgets.QMainWindow()
ui = Ui_AddFW()
ui.setupUi(AddFW)
AddFW.show()
sys.exit(app.exec_())
This happens because Add_FW exists only within the setupUi and retranslateUi methods. It works in MainWindow because you are declaring it below in
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow() <- HERE
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
One quick fix is to pass the AddFW object through connect this way :
self.Back.clicked.connect(lambda: self.BackToMain(AddFW))
But a better way to deal with this would be to inherit QMainWindow in both Ui_AddFW and Ui_MainWindow class due to which they both become an instance of QMainWindow and you wont have to pass the QMainWindow when you are instantiating it.
Check this out: PyQt class inheritance
Finally,
Instead of showing and hiding screens within each object, I would suggest creating a main.py and handle the show/hide logic there this way:
main.py
from AddFW import Ui_AddFW
from MainScreen import Ui_MainWindow
def handle_back_to_main():
add_fw.hide()
main_screen.show()
def handle_back_to_add_fw():
main_screen.hide()
add_fw.show()
add_fw = Ui_AddFW()
main_screen = Ui_MainWindow()
add_fw.Back.clicked.connect(handle_back_to_main)
main_screen.AddFWBtn.clicked.connect(handle_back_to_add_fw)
I made a simple mainWindow with the help of the qt designer and got the whole code using the pyuic5 option in the cmd.
I added this lineto the main part:
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
to be able to see my window correctly (without this its a whole mass).
In the properties inside qt designer i changed the sizePolicy values to be expanding, but when i try to run my application the sizePolicy is not working, it all stays in the left upper corner.
This is the code i got from the pyuic5:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CompanyCommanderLogin(object):
def setupUi(self, CompanyCommanderLogin):
CompanyCommanderLogin.setObjectName("CompanyCommanderLogin")
CompanyCommanderLogin.resize(252, 227)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(CompanyCommanderLogin.sizePolicy().hasHeightForWidth())
CompanyCommanderLogin.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(CompanyCommanderLogin)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 231, 171))
self.groupBox.setObjectName("groupBox")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(20, 40, 71, 16))
self.label.setObjectName("label")
self.label_3 = QtWidgets.QLabel(self.groupBox)
self.label_3.setGeometry(QtCore.QRect(20, 70, 41, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.groupBox)
self.label_4.setGeometry(QtCore.QRect(20, 100, 41, 16))
self.label_4.setObjectName("label_4")
self.lineEdit_x_location = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_x_location.setGeometry(QtCore.QRect(100, 70, 51, 20))
self.lineEdit_x_location.setObjectName("lineEdit_x_location")
self.lineEdit_y_location = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_y_location.setGeometry(QtCore.QRect(100, 100, 51, 20))
self.lineEdit_y_location.setObjectName("lineEdit_y_location")
self.pushButton_login = QtWidgets.QPushButton(self.groupBox)
self.pushButton_login.setGeometry(QtCore.QRect(140, 140, 71, 21))
self.pushButton_login.setStyleSheet("background-color: rgb(0, 209, 255);\n"
"color: rgb(255, 255, 255);\n"
"background-color: rgb(0, 0, 127);")
self.pushButton_login.setObjectName("pushButton_login")
self.comboBox = QtWidgets.QComboBox(self.groupBox)
self.comboBox.setGeometry(QtCore.QRect(100, 40, 51, 21))
self.comboBox.setObjectName("comboBox")
CompanyCommanderLogin.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(CompanyCommanderLogin)
self.menubar.setGeometry(QtCore.QRect(0, 0, 252, 18))
self.menubar.setObjectName("menubar")
CompanyCommanderLogin.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(CompanyCommanderLogin)
self.statusbar.setObjectName("statusbar")
CompanyCommanderLogin.setStatusBar(self.statusbar)
self.retranslateUi(CompanyCommanderLogin)
QtCore.QMetaObject.connectSlotsByName(CompanyCommanderLogin)
def retranslateUi(self, CompanyCommanderLogin):
_translate = QtCore.QCoreApplication.translate
CompanyCommanderLogin.setWindowTitle(_translate("CompanyCommanderLogin", "Company Commander Login"))
self.groupBox.setTitle(_translate("CompanyCommanderLogin", "Login"))
self.label.setText(_translate("CompanyCommanderLogin", "<html><head/><body><p><span style=\" font-size:9pt;\">Company Number:</span></p></body></html>"))
self.label_3.setText(_translate("CompanyCommanderLogin", "<html><head/><body><p><span style=\" font-size:9pt;\">X Location:</span></p></body></html>"))
self.label_4.setText(_translate("CompanyCommanderLogin", "<html><head/><body><p><span style=\" font-size:9pt;\">Y Location:</span></p></body></html>"))
self.pushButton_login.setText(_translate("CompanyCommanderLogin", "Login"))
if __name__ == "__main__":
import sys
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QtWidgets.QApplication(sys.argv)
CompanyCommanderLogin = QtWidgets.QMainWindow()
ui = Ui_CompanyCommanderLogin()
ui.setupUi(CompanyCommanderLogin)
CompanyCommanderLogin.show()
sys.exit(app.exec_())
What could be the problem with the sizePolicy? Is there another way to make my mainWindow the expand?
Picture for example (Here the login is in the left upper corner, I want it to be the whole window size)
As the docs points out:
The size policy of a widget is an expression of its willingness to be resized in various ways, and affects how the widget is treated by the layout engine. Each widget returns a QSizePolicy that describes the horizontal and vertical resizing policy it prefers when being laid out. You can change this for a specific widget by changing its QWidget::sizePolicy property.
The QSizePolicy work only in layouts, and in your case there are none.
So the solution is to create your design using the QXLayout, if you want to use it in Qt Designer you should read the Qt Designer Manual and especially section Using Layouts in Qt Designer.
In this case, since you have not provided the .ui that would allow me to use Qt Designer, I will quickly provide the solution from scratch
from PyQt5 import QtCore, QtGui, QtWidgets
class CompanyCommanderLogin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.groupbox = QtWidgets.QGroupBox(self.tr("Login"))
self.company_cb = QtWidgets.QComboBox()
sp = self.company_cb.sizePolicy()
sp.setHorizontalPolicy(QtWidgets.QSizePolicy.Expanding)
self.company_cb.setSizePolicy(sp)
self.xlocation_le = QtWidgets.QLineEdit()
self.ylocation_le = QtWidgets.QLineEdit()
self.login_button = QtWidgets.QPushButton(self.tr("Login"))
self.login_button.setStyleSheet(
"background-color: rgb(0, 209, 255);\n"
"color: rgb(255, 255, 255);\n"
"background-color: rgb(0, 0, 127);"
)
font = self.font()
font.setPointSize(9)
self.setFont(font)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.groupbox)
flay = QtWidgets.QFormLayout()
flay.addRow(
self.tr("Company Number:"), self.company_cb,
)
flay.addRow(
self.tr("X Location:"), self.xlocation_le,
)
flay.addRow(
self.tr("Y Location:"), self.ylocation_le,
)
lay = QtWidgets.QVBoxLayout()
lay.addLayout(flay)
lay.addWidget(self.login_button, alignment=QtCore.Qt.AlignHCenter)
lay.addStretch()
self.groupbox.setLayout(lay)
if __name__ == "__main__":
import sys
if hasattr(QtCore.Qt, "AA_EnableHighDpiScaling"):
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QtWidgets.QApplication(sys.argv)
w = CompanyCommanderLogin()
w.show()
sys.exit(app.exec_())
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
I am designing a GUI to capture an image from picamera, I am using PyQt5 to develop the GUI. I used camera.start_preview() function to see the live preview. After that I used a button named "Take" to capture the image and after capturing the image I showed the image in Qlabel by using self.label_2.setPixmap(QtGui.QPixmap()) command till this my code is working fine. Now I want to set the live preview of PiCamera into the same Qlabel, which I am using to show the captured image. Is it possible to set the live preview inside a QLabel?
After googling I found PIL can be used to stream live preview inside an window, but I have no idea how to implement it.
from PyQt5 import QtCore, QtGui, QtWidgets
from picamera import PiCamera
import time
from time import sleep
import gpiozero
from gpiozero import Button
from PIL import Image
import cups
import os
camera = PiCamera()
camera.sensor_mode = 2
camera.brightness = 70
camera.contrast = 20
photoHeight = 1944
photoWidth = 2592
class clsPicCount(object):
countpic=0
def __init__(self):
clsPicCount.countpic=clsPicCount.countpic+1
if clsPicCount.countpic > 1:
clsPicCount.countpic = 0
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1366, 768)
MainWindow.setMinimumSize(QtCore.QSize(1366, 768))
MainWindow.setMaximumSize(QtCore.QSize(1366, 768))
font = QtGui.QFont()
font.setUnderline(False)
font.setStrikeOut(False)
MainWindow.setFont(font)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("Photo.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.retake = QtWidgets.QPushButton(self.centralwidget)
self.retake.setGeometry(QtCore.QRect(320, 680, 211, 71))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.retake.setFont(font)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("retake.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
self.retake.setIcon(icon1)
self.retake.setIconSize(QtCore.QSize(50, 50))
self.retake.setObjectName("retake")
self.take = QtWidgets.QPushButton(self.centralwidget)
self.take.setGeometry(QtCore.QRect(550, 680, 211, 71))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.take.setFont(font)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("take.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
self.take.setIcon(icon2)
self.take.setIconSize(QtCore.QSize(60, 60))
self.take.setObjectName("take")
self.print = QtWidgets.QPushButton(self.centralwidget)
self.print.setGeometry(QtCore.QRect(780, 680, 211, 71))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.print.setFont(font)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap("print.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
self.print.setIcon(icon3)
self.print.setIconSize(QtCore.QSize(50, 50))
self.print.setCheckable(True)
self.print.setObjectName("print")
self.settings = QtWidgets.QPushButton(self.centralwidget)
self.settings.setGeometry(QtCore.QRect(1220, 690, 121, 51))
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(True)
font.setWeight(75)
self.settings.setFont(font)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap("settings.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
self.settings.setIcon(icon4)
self.settings.setIconSize(QtCore.QSize(30, 30))
self.settings.setObjectName("settings")
self.heading = QtWidgets.QLabel(self.centralwidget)
self.heading.setGeometry(QtCore.QRect(390, 20, 581, 31))
self.heading.setObjectName("heading")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(230, 70, 900, 600))
self.label_2.setText("")
self.label_2.setPixmap(QtGui.QPixmap("photobooth.jpg"))
self.label_2.setScaledContents(True)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(0, 0, 1361, 771))
self.label_3.setText("")
self.label_3.setPixmap(QtGui.QPixmap("background.png"))
self.label_3.setObjectName("label_3")
self.label_3.raise_()
self.retake.raise_()
self.take.raise_()
self.print.raise_()
self.settings.raise_()
self.heading.raise_()
self.label_2.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#Defining functions of our buttons
self.take.clicked.connect(self.startPreview)
#Initializing Printer
conn = cups.Connection ()
printers = conn.getPrinters ()
printer_name = list(printers)[0]
for printer in printers:
print (printer, printers[printer]["device-uri"])
#Code Block for live preview and image capture
def startPreview(self):
p=clsPicCount()
print(clsPicCount.countpic)
if clsPicCount.countpic == 1:
camera.start_preview(fullscreen=False, window=(10,0,320,240))
else:
filename = time.strftime("%Y%m%d-%H%M%S")
print (filename)
camera.capture('/home/pi/Desktop/%s.jpg'%filename, resize = (photoWidth, photoHeight))
camera.stop_preview()
self.label_2.setPixmap(QtGui.QPixmap('/home/pi/Desktop/%s.jpg'%filename))
self.label_2.setScaledContents(True)
#self.label_3.raise_()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "PhotoBooth"))
self.retake.setText(_translate("MainWindow", "RETAKE"))
self.take.setText(_translate("MainWindow", "TAKE"))
self.print.setText(_translate("MainWindow", "PRINT"))
self.settings.setText(_translate("MainWindow", "SETTINGS"))
self.heading.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:14pt; font-weight:600; color:#ffffff;\">TECH MECH SERVICES PVT LTD.</span></p></body></html>"))
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_())