This question already has an answer here:
How to fix error in my pyqt programm (first argument of unbound method must have type 'QDialog') ?
(1 answer)
Closed 3 years ago.
I can't use setWindowFlags with my QDialog widget. am trying to hide the close button or remove the whole frame so the user can't close it using the default method.
I've tried adding one of those two lines inside the setupUi function for my class :
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
and
self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False) but both gave me the same error.
Here is my code for a better inspection:
import os
import sys
import psycopg2
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMessageBox
import backoffice
class Ui_Dialog(object):
def setupUi(self, Dialog):
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
Dialog.setObjectName("Dialog")
Dialog.resize(400, 274)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(self.resource_path("./images/pos_logo_small.png")), QtGui.QIcon.Normal,
QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
Dialog.setLayoutDirection(QtCore.Qt.RightToLeft)
Dialog.setStyleSheet("background:#a1d0f4;")
self.gridLayout = QtWidgets.QGridLayout(Dialog)
self.gridLayout.setObjectName("gridLayout")
self.formLayout = QtWidgets.QFormLayout()
self.formLayout.setHorizontalSpacing(4)
self.formLayout.setObjectName("formLayout")
self.label_2 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setFamily("Shorooq_N1")
font.setPointSize(18)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
self.label_3 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setFamily("Shorooq_N1")
font.setPointSize(18)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_3)
self.lineEdit = QtWidgets.QLineEdit(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
self.lineEdit.setSizePolicy(sizePolicy)
self.lineEdit.setStyleSheet("background:white;")
self.lineEdit.setObjectName("lineEdit")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lineEdit)
self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
self.lineEdit_2.setSizePolicy(sizePolicy)
self.lineEdit_2.setStyleSheet("background:white;")
self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)
self.lineEdit_2.setObjectName("lineEdit_2")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.lineEdit_2)
self.closeToolButton = QtWidgets.QToolButton(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.closeToolButton.sizePolicy().hasHeightForWidth())
self.closeToolButton.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Shorooq_N1")
font.setPointSize(18)
font.setBold(False)
font.setWeight(50)
self.closeToolButton.setFont(font)
self.closeToolButton.setStyleSheet("background:red;color:white;")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(self.resource_path("./images/close-window-256.ico")), QtGui.QIcon.Normal,
QtGui.QIcon.Off)
self.closeToolButton.setIcon(icon1)
self.closeToolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
self.closeToolButton.setObjectName("closeToolButton")
self.closeToolButton.clicked.connect(self.exit_app)
self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.closeToolButton)
self.logInToolButton = QtWidgets.QToolButton(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.logInToolButton.sizePolicy().hasHeightForWidth())
self.logInToolButton.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Shorooq_N1")
font.setPointSize(16)
self.logInToolButton.setFont(font)
self.logInToolButton.setStyleSheet("background:#0a74c4;color:white;")
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(self.resource_path("./images/check-mark-11-256.ico")), QtGui.QIcon.Normal,
QtGui.QIcon.Off)
self.logInToolButton.setIcon(icon2)
self.logInToolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
self.logInToolButton.setObjectName("logInToolButton")
self.dialog = Dialog
self.logInToolButton.clicked.connect(self.log_in)
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.logInToolButton)
self.gridLayout.addLayout(self.formLayout, 1, 1, 1, 1)
self.label = QtWidgets.QLabel(Dialog)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 1, 1, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def exit_app(self):
QtCore.QCoreApplication.instance().quit()
def log_in(self):
print('activated')
try:
connection = psycopg2.connect(user="*******",
password="********",
host="127.0.0.1",
port="5432",
database="********")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from users"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from users table using cursor.fetchall")
user_records = cursor.fetchall()
print("Print each row and it's columns values")
input_username = self.lineEdit.text()
input_password = self.lineEdit_2.text()
for row in user_records:
if row[1] == input_username:
if row[2] == input_password:
backoffice.isAuthenticated = True
print('logged in ')
self.dialog.close()
else:
pass
print(input)
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# closing database connection.
connection = psycopg2.connect(user="*********",
password="*******",
host="127.0.0.1",
port="5432",
database="*******")
cursor = connection.cursor()
if (connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Vision Store Manager"))
self.label_2.setText(_translate("Dialog", "إسم المستخدم"))
self.label_3.setText(_translate("Dialog", "كلمة المرور"))
self.closeToolButton.setText(_translate("Dialog", "خروج"))
self.logInToolButton.setText(_translate("Dialog", "تسجيل الدخول"))
self.label.setText(_translate("Dialog",
"<html><head/><body><p><img src=\":/images/images/logo_small.png\"/></p></body></html>"))
#staticmethod
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
import login_rcs_rc
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_())
Getting the error AttributeError: 'Ui_Dialog' object has no attribute 'setWindowFlags' when executing the line : self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
UPDATE
I changed :
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
To
the_login = QtWidgets.QDialog
the_login.setWindowFlags(QtCore.Qt.FramelessWindowHint)
and the error now is:TypeError: setWindowFlags(self, Union[Qt.WindowFlags, Qt.WindowType]): first argument of unbound method must have type 'QWidget'
You do your inheritance wrong.
How it should be in declarations?
class Ui_Dialog should inherit all properties from QtWidgets.QDialog. Your Dialog variable should be self. You shouldn't call your functions with Dialog variable.
Your main mistakes:
class Ui_Dialog => class Ui_Dialog(QtWidgets.QDialog)
self.gridLayout = QtWidgets.QGridLayout(Dialog) => self.gridLayout = QtWidgets.QGridLayout(self)
#all should be changed like this
ui.setupUi(Dialog)=>ui.setupUi()
Code:
class Ui_Dialog(QtWidgets.QDialog):
def setupUi(self):
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setObjectName("Dialog")
self.resize(400, 274)
self.gridLayout = QtWidgets.QGridLayout(self)
... #your stuff
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
#Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi()
ui.show()
sys.exit(app.exec_())
Related
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)
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'messagerGUI.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
# ""
from PyQt5 import QtCore, QtGui, QtWidgets
import socket
import threading
class Ui_MainWindow(object):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
header = 12
connections = []
ip = socket.gethostname()
port = 1234
connections_allowed = 3
sock.bind((ip, port))
sock.listen(connections_allowed)
new_message = False
def start(self):
while True:
self.conn, self.addr = self.sock.accept()
threading.Thread(target=self.receive_data, args=[
self.conn], daemon=True).start()
self.connections.append(self.conn)
def receive_data(self, conn):
self.reply = ""
while True:
try:
message_lenth = conn.recv(self.header)
lenth_of_message = message_lenth.decode("utf-8")
if not message_lenth:
break
elif message_lenth:
data = conn.recv(int(lenth_of_message))
self.reply = data.decode("utf-8")
print(self.reply)
self.new_message = True
for connection in self.connections:
if connection != conn:
connection.send(message_lenth.encode("utf-8"))
connection.send(self.reply.encode("utf-8"))
except:
break
def packing_data_lenth(self, text):
return len(text) * 4
def send_data(self, data):
try:
for connection in self.connections:
connection.send(
bytes(str(self.packing_data_lenth(data)), "utf-8"))
connection.send(bytes(data, "utf-8"))
except:
pass
def setupUi(self, MainWindow):
threading.Thread(target=self.start, daemon=True).start()
MainWindow.setObjectName("MainWindow")
MainWindow.resize(499, 367)
MainWindow.setStyleSheet("background-color: #113e4a;")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setContentsMargins(5, 5, 5, 5)
self.horizontalLayout.setSpacing(5)
self.horizontalLayout.setObjectName("horizontalLayout")
self.info = QtWidgets.QWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.info.sizePolicy().hasHeightForWidth())
self.info.setSizePolicy(sizePolicy)
self.info.setMinimumSize(QtCore.QSize(178, 357))
self.info.setStyleSheet("background-color: #429178;\n"
"border-radius: 2px;")
self.info.setObjectName("info")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.info)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label_3 = QtWidgets.QLabel(self.info)
self.label_3.setObjectName("label_3")
self.verticalLayout_3.addWidget(self.label_3)
spacerItem = QtWidgets.QSpacerItem(
20, 317, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem)
self.horizontalLayout.addWidget(self.info)
self.message_widget()
self.chat_area = QtWidgets.QWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.chat_area.sizePolicy().hasHeightForWidth())
self.chat_area.setSizePolicy(sizePolicy)
self.chat_area.setMinimumSize(QtCore.QSize(306, 0))
self.chat_area.setStyleSheet("background-color: #429178;")
self.chat_area.setObjectName("chat_area")
self.verticalLayout = QtWidgets.QVBoxLayout(self.chat_area)
self.verticalLayout.setContentsMargins(2, 2, 2, 2)
self.verticalLayout.setSpacing(1)
self.verticalLayout.setObjectName("verticalLayout")
self.messages_area = QtWidgets.QScrollArea(self.chat_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.MinimumExpanding)
sizePolicy.setHeightForWidth(
self.messages_area.sizePolicy().hasHeightForWidth())
self.messages_area.setSizePolicy(sizePolicy)
self.messages_area.setMinimumSize(QtCore.QSize(0, 259))
self.messages_area.setStyleSheet("background-color: #113e4a;")
self.messages_area.setWidgetResizable(True)
self.messages_area.setObjectName("messages_area")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 300, 316))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.scrollAreaWidgetContents.sizePolicy().hasHeightForWidth())
self.scrollAreaWidgetContents.setSizePolicy(sizePolicy)
self.scrollAreaWidgetContents.setLayoutDirection(QtCore.Qt.LeftToRight)
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(
self.scrollAreaWidgetContents)
self.verticalLayout_2.setSizeConstraint(
QtWidgets.QLayout.SetNoConstraint)
self.verticalLayout_2.setSpacing(6)
self.verticalLayout_2.setObjectName("verticalLayout_2")
spacerItem1 = QtWidgets.QSpacerItem(
20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.MinimumExpanding)
self.verticalLayout_2.addItem(spacerItem1)
self.messages_area.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout.addWidget(self.messages_area)
self.input_area = QtWidgets.QWidget(self.chat_area)
self.input_area.setMinimumSize(QtCore.QSize(0, 30))
self.input_area.setObjectName("input_area")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.input_area)
self.horizontalLayout_2.setContentsMargins(1, 1, 1, 1)
self.horizontalLayout_2.setSpacing(1)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.userInput = QtWidgets.QLineEdit(self.input_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.userInput.sizePolicy().hasHeightForWidth())
self.userInput.setSizePolicy(sizePolicy)
self.userInput.setMinimumSize(QtCore.QSize(22, 32))
font = QtGui.QFont()
font.setPointSize(12)
self.userInput.setFont(font)
self.userInput.setStyleSheet("background-color: rgb(17, 62, 74);\n"
"color: #d0e8ce;\n"
"border: 0px;")
self.userInput.setInputMethodHints(QtCore.Qt.ImhNone)
self.userInput.setFrame(True)
self.userInput.setDragEnabled(True)
self.userInput.setPlaceholderText("Type a message")
self.userInput.setObjectName("userInput")
self.horizontalLayout_2.addWidget(self.userInput)
self.sendButton = QtWidgets.QPushButton(self.input_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.sendButton.sizePolicy().hasHeightForWidth())
self.sendButton.setSizePolicy(sizePolicy)
self.sendButton.setMinimumSize(QtCore.QSize(12, 32))
font = QtGui.QFont()
font.setPointSize(12)
self.sendButton.setFont(font)
self.sendButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.sendButton.setMouseTracking(True)
self.sendButton.setObjectName("sendButton")
self.sendButton.clicked.connect(self.get_user_input)
self.horizontalLayout_2.addWidget(self.sendButton)
self.verticalLayout.addWidget(self.input_area)
self.horizontalLayout.addWidget(self.chat_area)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
In this part(function message_widget) i get an error:
self.widget = QtWidgets.QWidget(self.scrollAreaWidgetContents)
AttributeError: 'Ui_MainWindow' object has no attribute 'scrollAreaWidgetContents'
Even though i did something similar in the get_user_input function,
i know the code is a mess but the only part that is not working is this part,
the socket server and client are both working properly, i tested printing the
text received in the terminal, so yeah, i wanna know why do i get this error?
def message_widget(self):
self.widget = QtWidgets.QWidget(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.widget.sizePolicy().hasHeightForWidth())
self.widget.setSizePolicy(sizePolicy)
self.widget.setMinimumSize(QtCore.QSize(158, 25))
self.widget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.widget.setStyleSheet(
"background-color: #d35439;\n" "border-radius: 4px;")
self.widget.setObjectName("widget")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label = QtWidgets.QLabel(self.widget)
self.label.setScaledContents(True)
self.label.setObjectName("label")
self.label.text(self.reply)
self.horizontalLayout_3.addWidget(self.label)
self.verticalLayout_2.addWidget(self.widget)
def get_user_input(self):
self.user_msg = self.userInput.text()
threading.Thread(target=self.send_data, args=[
self.user_msg], daemon=True).start()
self.widget_2 = QtWidgets.QWidget(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.widget_2.sizePolicy().hasHeightForWidth())
self.widget_2.setSizePolicy(sizePolicy)
self.widget_2.setMinimumSize(QtCore.QSize(182, 25))
self.widget_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.widget_2.setStyleSheet("background-color: rgb(236, 172, 55);\n"
"border-radius: 4px;")
self.widget_2.setObjectName("widget_2")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.widget_2)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.label_2 = QtWidgets.QLabel(self.widget_2)
self.label_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_2.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.label_2.setObjectName("label_2")
self.label_2.setText(self.user_msg)
self.horizontalLayout_4.addWidget(self.label_2)
self.verticalLayout_2.addWidget(self.widget_2)
self.userInput.setText("")
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "PadoMessager"))
self.label_3.setText(_translate("MainWindow", "Server"))
self.sendButton.setText(_translate("MainWindow", "Send"))
self.sendButton.setShortcut(_translate("MainWindow", "Return"))
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_())
You think it exists, but when you call message_widget() it does not exist yet.
In fact, you are calling that function before this line:
self.scrollAreaWidgetContents = QtWidgets.QWidget()
So, it could work if you put that function at least after creating that widget.
Unfortunately, there are other serious issues with your code.
The most important one is that you are modifying the output of pyuic to create your program, which is highly discouraged (and the WARNING message at the beginning should be a hint).
The python scripts generated from UI files should NEVER be edited, but used as an import in your actual program files. The most obvious reason is that as soon as you want to do some changes in the ui, you'll find yourself in the mess of trying to merge the new generated code with what you've written so far.
To know more about this, read the documentation about using Designer.
Other issues in your code:
threading in Qt should be used with Qt's own QThread as much as possible;
UI objects should never be accessed nor modified by an external thread; to do that you have to use a QThread, and communicate with the main Qt thread using signals and slots;
QLabel.text() does not accept parameters, as it is used to access the text property; to set the text of a label, use setText();
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_())
This question already has answers here:
Close and Open new Window PYQT5
(2 answers)
Closed 3 years ago.
I am currently trying to get a button press in one qt window to open a second window which is in another python file. My layout code was generated by converting a ui made in Qt designer to python.
My select feature code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'movie_design.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import add_entry
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(597, 522)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(160, 40, 291, 51))
font = QtGui.QFont()
font.setPointSize(14)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
font.setKerning(True)
self.label.setFont(font)
self.label.setLineWidth(1)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(170, 110, 261, 91))
font = QtGui.QFont()
font.setPointSize(12)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(170, 230, 261, 91))
font = QtGui.QFont()
font.setPointSize(12)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(170, 350, 261, 91))
font = QtGui.QFont()
font.setPointSize(12)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 597, 26))
self.menubar.setObjectName("menubar")
self.menuMenu = QtWidgets.QMenu(self.menubar)
self.menuMenu.setObjectName("menuMenu")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.menubar.addAction(self.menuMenu.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton_2.clicked.connect(self.add)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Movie Database Program"))
self.pushButton.setText(_translate("MainWindow", "Delete Record"))
self.pushButton_2.setText(_translate("MainWindow", "Add Record"))
self.pushButton_3.setText(_translate("MainWindow", "Search Records"))
self.menuMenu.setTitle(_translate("MainWindow", "Menu"))
def add(self):
add_entry.add_entry()
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
app.exec_()
if __name__ == "__main__":
main()
As you can see, I have created a button that when pressed calls the function in the program "add_entry.py"
Add entry.py code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'add_entry.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(555, 418)
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(10, 30, 533, 28))
font = QtGui.QFont()
font.setPointSize(14)
self.label.setFont(font)
self.label.setTextFormat(QtCore.Qt.AutoText)
self.label.setScaledContents(False)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.formLayoutWidget = QtWidgets.QWidget(Dialog)
self.formLayoutWidget.setGeometry(QtCore.QRect(30, 70, 501, 321))
self.formLayoutWidget.setObjectName("formLayoutWidget")
self.formLayout = QtWidgets.QFormLayout(self.formLayoutWidget)
self.formLayout.setContentsMargins(0, 0, 0, 0)
self.formLayout.setObjectName("formLayout")
self.label_2 = QtWidgets.QLabel(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label_2)
self.MovieTitle = QtWidgets.QLineEdit(self.formLayoutWidget)
self.MovieTitle.setObjectName("MovieTitle")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.MovieTitle)
self.label_3 = QtWidgets.QLabel(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_3)
self.MovieStudio = QtWidgets.QLineEdit(self.formLayoutWidget)
self.MovieStudio.setObjectName("MovieStudio")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.MovieStudio)
self.label_4 = QtWidgets.QLabel(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_4)
self.dateEdit = QtWidgets.QDateEdit(self.formLayoutWidget)
self.dateEdit.setObjectName("dateEdit")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.dateEdit)
self.label_5 = QtWidgets.QLabel(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label_5)
self.ProductionCost = QtWidgets.QSpinBox(self.formLayoutWidget)
self.ProductionCost.setMaximum(1000000000)
self.ProductionCost.setObjectName("ProductionCost")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.ProductionCost)
self.label_6 = QtWidgets.QLabel(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.label_6)
self.BoxOfficeRevenue = QtWidgets.QSpinBox(self.formLayoutWidget)
self.BoxOfficeRevenue.setMaximum(1000000000)
self.BoxOfficeRevenue.setObjectName("BoxOfficeRevenue")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.BoxOfficeRevenue)
self.label_7 = QtWidgets.QLabel(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label_7.setFont(font)
self.label_7.setObjectName("label_7")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.label_7)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.No = QtWidgets.QRadioButton(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.No.setFont(font)
self.No.setObjectName("No")
self.horizontalLayout.addWidget(self.No)
self.Yes = QtWidgets.QRadioButton(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.Yes.setFont(font)
self.Yes.setObjectName("Yes")
self.horizontalLayout.addWidget(self.Yes)
self.formLayout.setLayout(5, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout)
self.label_8 = QtWidgets.QLabel(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label_8.setFont(font)
self.label_8.setObjectName("label_8")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.label_8)
self.classificationBox = QtWidgets.QComboBox(self.formLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.classificationBox.setFont(font)
self.classificationBox.setObjectName("classificationBox")
self.classificationBox.addItem("")
self.classificationBox.addItem("")
self.classificationBox.addItem("")
self.classificationBox.addItem("")
self.classificationBox.addItem("")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.classificationBox)
self.pushButton = QtWidgets.QPushButton(self.formLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setObjectName("pushButton")
self.formLayout.setWidget(7, QtWidgets.QFormLayout.SpanningRole, self.pushButton)
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", "<html><head/><body><p><span style=\" font-size:12pt; text-decoration: underline;\">Add Entry</span></p></body></html>"))
self.label_2.setText(_translate("Dialog", "Movie Title"))
self.label_3.setText(_translate("Dialog", "Movie Studio"))
self.label_4.setText(_translate("Dialog", "Release Date"))
self.label_5.setText(_translate("Dialog", "Production Cost (m$)"))
self.label_6.setText(_translate("Dialog", "Box Office Revenue (m$)"))
self.label_7.setText(_translate("Dialog", "Have you seen this movie?"))
self.No.setText(_translate("Dialog", "Yes"))
self.Yes.setText(_translate("Dialog", "No"))
self.label_8.setText(_translate("Dialog", "Classification (Age Rating)"))
self.classificationBox.setItemText(0, _translate("Dialog", "U"))
self.classificationBox.setItemText(1, _translate("Dialog", "PG"))
self.classificationBox.setItemText(2, _translate("Dialog", "12"))
self.classificationBox.setItemText(3, _translate("Dialog", "15"))
self.classificationBox.setItemText(4, _translate("Dialog", "18"))
self.pushButton.setText(_translate("Dialog", "Add Entry"))
def add_entry():
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
app.exec_()
if __name__ == "__main__":
add_entry()
The issue is that the when the button is pressed, the program crashes, telling me that "Event loop already running". How do I fix this?
Qt, like many GUI frameworks, is based on an event loop which is started with app.exec_() and then waits for events to react to (both from the user or the system).
For each Qt program there should always be a single and only QApplication instance running its event loop.
With your implementation, each time you press the button, you're trying to create and launch a new QApplication, and Qt will not allow you for the reason above.
Nonetheless, the problem with your code is somewhere else, as you are using the generated UI code in the wrong way: those files should never be used as a basis to create your program code (in fact, you should always leave them as they are).
I suggest you to carefully read the official documentation about using Designer to understand how to use those files.
Regenerate the UI files with pyuic, and then create a new script that will probably contain something similar to this:
from PyQt5 import QtWidgets
from ui_mainwindow import Ui_MainWindow
from ui_dialog import Ui_Dialog
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton_2.clicked.connect(self.add)
def add(self):
dialog = Dialog(self)
dialog.exec_()
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
In this example I used the third method (multiple inheritance approach) explained in the documentation given above.
I have two files and I want to return an array from Dialog of Bitacora to Main. In some part of the Main code calls Bitacora. Bitacora have a textEdit. I need to return these values.
I hope that you can help me guys.
File: Main.py
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import Qt
from dbFuncs import *
from demoUI import *
from PandasModel import *
from dataLogger import *
from bitacorasend import Ui_Dialog
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
#QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
'''Variables for DB'''
'''Table Config'''
self.dataTable.setColumnCount(1)
self.dataTable.setRowCount(5)
self.dataTable.setHorizontalHeaderLabels(["Medición"])
self.dataTable.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)
self.dataTable.horizontalHeader().setStretchLastSection(True)
self.dataTable.verticalHeader().setStretchLastSection(True)
'''Buttons signals'''
self.saveButton.clicked.connect(self.savePressed)
def bitacora(self):
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog,["data","data","data","data"])
Dialog.exec_()
def savePressed(self):
self.bitacora()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()
File: Bitacora.py
from PyQt5 import QtCore, QtGui, QtWidgets
#import time
class Ui_Dialog(object):
def setupUi(self, Dialog, datos):
self.data = datos
self.Dialog = Dialog
Dialog.setObjectName("Dialog")
Dialog.resize(617, 405)
self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(10)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.label_2 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.label_5 = QtWidgets.QLabel(Dialog)
self.label_5.setAlignment(QtCore.Qt.AlignCenter)
self.label_5.setObjectName("label_5")
self.verticalLayout.addWidget(self.label_5)
self.label_3 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft)
self.label_3.setObjectName("label_3")
self.verticalLayout.addWidget(self.label_3)
self.textEdit = QtWidgets.QTextEdit(Dialog)
self.textEdit.setMaximumSize(QtCore.QSize(16777215, 100))
self.textEdit.setObjectName("textEdit")
self.verticalLayout.addWidget(self.textEdit)
self.label_4 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft)
self.label_4.setObjectName("label_4")
self.verticalLayout.addWidget(self.label_4)
self.textEdit_2 = QtWidgets.QTextEdit(Dialog)
self.textEdit_2.setObjectName("textEdit_2")
self.verticalLayout.addWidget(self.textEdit_2)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout.addWidget(self.buttonBox)
self.retranslateUi(Dialog)
self.buttonBox.accepted.connect(self.save)
self.buttonBox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def save(self):
print("Return here")
self.Dialog.close()
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Punto Fuera de Control"))
self.label_2.setText(_translate("Dialog", "Bitacora de Proceso"))
self.label_5.setText(_translate("Dialog", "Cualquier cambio en mano de obra, materiales, medio ambiente, métodos o máquinas debe ser anotado"))
self.label_3.setText(_translate("Dialog", "Causa:"))
self.textEdit.setText(_translate("Dialog", ""))
self.label_4.setText(_translate("Dialog", "Correcciones:"))
self.textEdit_2.setHtml(_translate("Dialog", ""))
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_())
Try it:
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import Qt
#from dbFuncs import *
#from demoUI import *
#from PandasModel import *
#from dataLogger import *
#import time
#from bitacorasend import Ui_Dialog
class Ui_Dialog(object):
def setupUi(self, Dialog, datos):
self.data = datos
self.Dialog = Dialog
Dialog.setObjectName("Dialog")
Dialog.resize(617, 405)
self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(10)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.label_2 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.label_5 = QtWidgets.QLabel(Dialog)
self.label_5.setAlignment(QtCore.Qt.AlignCenter)
self.label_5.setObjectName("label_5")
self.verticalLayout.addWidget(self.label_5)
self.label_3 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft)
self.label_3.setObjectName("label_3")
self.verticalLayout.addWidget(self.label_3)
self.textEdit = QtWidgets.QTextEdit(Dialog)
self.textEdit.setMaximumSize(QtCore.QSize(16777215, 100))
self.textEdit.setObjectName("textEdit")
self.verticalLayout.addWidget(self.textEdit)
self.label_4 = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft)
self.label_4.setObjectName("label_4")
self.verticalLayout.addWidget(self.label_4)
self.textEdit_2 = QtWidgets.QTextEdit(Dialog)
self.textEdit_2.setObjectName("textEdit_2")
self.verticalLayout.addWidget(self.textEdit_2)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout.addWidget(self.buttonBox)
self.retranslateUi(Dialog)
self.buttonBox.accepted.connect(self.save)
self.buttonBox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def save(self):
print("Return here")
self.Dialog.close()
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Punto Fuera de Control"))
self.label_2.setText(_translate("Dialog", "Bitacora de Proceso"))
self.label_5.setText(_translate("Dialog", "Cualquier cambio en mano de obra, materiales, medio ambiente, métodos o máquinas debe ser anotado"))
self.label_3.setText(_translate("Dialog", "Causa:"))
self.textEdit.setText(_translate("Dialog", ""))
self.label_4.setText(_translate("Dialog", "Correcciones:"))
self.textEdit_2.setHtml(_translate("Dialog", ""))
class MainWindow(QtWidgets.QMainWindow): #, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
#QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
# self.setupUi(self)
'''Variables for DB'''
centralWidget = QtWidgets.QWidget(self)
self.setCentralWidget(centralWidget)
self.dataTable = QtWidgets.QTableWidget(self)
self.saveButton = QtWidgets.QPushButton("saveButton", self)
layout = QtWidgets.QGridLayout(centralWidget)
layout.addWidget(self.dataTable)
layout.addWidget(self.saveButton)
'''Table Config'''
self.dataTable.setColumnCount(1)
self.dataTable.setRowCount(5)
self.dataTable.setHorizontalHeaderLabels(["Medición"])
self.dataTable.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)
self.dataTable.horizontalHeader().setStretchLastSection(True)
self.dataTable.verticalHeader().setStretchLastSection(True)
'''Buttons signals'''
self.saveButton.clicked.connect(self.savePressed)
def bitacora(self):
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog,["data","data","data","data"])
Dialog.exec_()
print(ui.textEdit.toPlainText()) # <---
print(ui.textEdit_2.toPlainText()) # <---
def savePressed(self):
self.bitacora()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()