I have a python script that runs fine when launched on its own.
I want to write a bash script that will run one python script, and then another when the first ends.
Bash script:
#!/bin/bash
python /FILEPATH/FILE1.py ;
python /FILEPATH/FILE2.py
When I execute the bash file, I get this error message:
File "Filename of first python script", line 149
self.label_2.setText(f'Invalid: {input_str}')
File "Filename of second python script", line 139
self.label_2.setText(f'Invalid: {input_str}')
with an accent pointing at the last single quote of both lines.
(The scripts are identical, save for the values contained in the dictionary.
Here is that code
import sys
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import QMovie, QPixmap
from PyQt5.QtWidgets import *
WINDOW_STYLE = '''
background-color:black;
color:white;
'''
class Ui_Widget(QWidget):
# You need to change this
CARD_DICT = {
# PIN: IMAGE_PATH
'1360739516458': 'images/1.png', # Right lung
'1360743335192': 'images/2.png', # Left lung apex
'1360341692930': 'images/3.png', # Left heart
'136073147157207': 'images/4.png', # Spleen
'136075353245': 'images/5.png', # Subxiphoid cardiac
# '136072179130241': 'images/6.png', # Diaphragm?
# '136073133188248': 'images/7.png', # Supra umbilicus
# '136035223197177': 'images/8.png', # right lateral
# '1360341562547': 'images/9.png', # left lateral
# '13607311245156': 'images/10.png', # Sub umbilicus
# the following are for testing purposes only
'60013620412116': 'images/6.png', # Diaphragm?
'13603447120253': 'images/7.png', # Supra umbilicus
'1360341002204': 'images/8.png', # right lateral
'13607217912415': 'images/9.png', # left lateral
'136073209222206': 'images/10.png', # Sub umbilicus
}
def __init__(self):
super(Ui_Widget, self).__init__()
self.setWindowTitle('Simulated Ultrasound')
# Full screen
self.setWindowState(Qt.WindowMaximized)
# No close, minimize and miximaze window button
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
self.setStyleSheet(WINDOW_STYLE)
self.setupUi(self)
def setupUi(self, Widget):
Widget.setObjectName("Widget")
Widget.resize(800, 600)
self.verticalLayout_2 = QtWidgets.QVBoxLayout(Widget)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Widget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(50)
self.label.setFont(font)
self.label.setFrameShape(QtWidgets.QFrame.NoFrame)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.verticalLayout_2.addLayout(self.gridLayout)
self.lineEdit = QtWidgets.QLineEdit(Widget)
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.setMinimumSize(QtCore.QSize(780, 0))
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout_2.addWidget(self.lineEdit)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.horizontalLayout.setSpacing(10)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label_2 = QtWidgets.QLabel(Widget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum
)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
self.label_2.setSizePolicy(sizePolicy)
self.label_2.setMinimumSize(QtCore.QSize(0, 10))
self.label_2.setObjectName("label_2")
self.horizontalLayout.addWidget(self.label_2)
spacerItem = QtWidgets.QSpacerItem(
40, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum
)
self.horizontalLayout.addItem(spacerItem)
self.pushButton = QtWidgets.QPushButton(Widget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(0, 26))
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.verticalLayout_2.addLayout(self.horizontalLayout)
self.retranslateUi(Widget)
QtCore.QMetaObject.connectSlotsByName(Widget)
# I think this is the line to change to make it launch another script
self.pushButton.pressed.connect(Widget.close) # type: ignore
# self.pushButton.pressed.connect(Widget.post_intervention) # type: ignore
# Check every time the text line input changed
self.lineEdit.textChanged.connect(self.submit_pass) # type: ignore
def retranslateUi(self, Widget):
_translate = QtCore.QCoreApplication.translate
Widget.setWindowTitle(_translate("Widget", "Widget"))
self.label.setText(_translate("Widget", "Scan patient to begin"))
self.lineEdit.setPlaceholderText(_translate("Widget", "PIN Phrase"))
self.label_2.setText(_translate("Widget", "Arthur: PRE-intervention"))
self.pushButton.setText(_translate("Widget", "Click here after performing interventions"))
def submit_pass_str(self, input_str):
"""here the application accept user input"""
if input_str in self.CARD_DICT:
self.display_image(self.CARD_DICT[input_str])
self.label_2.setText('')
else:
self.label_2.setText(f'Invalid: {input_str}')
def display_image(self, path):
name, ext = os.path.splitext(path)
if ext and ext.lower() == '.gif':
movie = QMovie(path)
self.label.setMovie(movie)
movie.start()
else:
image = QPixmap(path)
self.label.setPixmap(image)
self.label.setMinimumSize(1, 1)
def submit_pass(self):
"""Usage example using PIN Phrase input form"""
self.submit_pass_str(self.lineEdit.text())
app = QApplication(sys.argv)
window = Ui_Widget()
window.show()
# sys.exit(post_intervention())
sys.exit(app.exec_())
Related
I'm developing some custom software that involves creating a workspace and working in it. I want to display all the existing workSpace directories in a dynamic scrollarea grid comprised of buttons that changes the positions of the buttons depending on the amount of screen real estate the scrollarea is taking up so that as many buttons as possible are inserted in the highest possible row.( So basically like the file explorer changes the layout of the folders and files to fit the screen in a grid depending on how you resize the window) I tried doing this using a gridlayout inside the scrollarea. I also tried to add qhboxlayouts in a qvboxlayout to no avail since I had no idea how to check whether there is space for another button to remove one from a lower qhboxlayout and append to a higher one.
This is my current code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
class Ui_AutoCal(object):
def setupUi(self, AutoCal):
AutoCal.setObjectName("AutoCal")
AutoCal.resize(513, 551)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(AutoCal.sizePolicy().hasHeightForWidth())
AutoCal.setSizePolicy(sizePolicy)
AutoCal.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))
AutoCal.setStyleSheet("*{\n"
"background-color: rgb(54, 54, 54);\n"
"color:rgb(255,255,255)\n"
"}\n"
"\n"
"QPushButton\n"
"{\n"
"border-radius: 25px;\n"
"}\n"
"\n"
"QLineEdit\n"
"{\n"
"color:rgb(0,0,0)\n"
"}")
self.centralwidget = QtWidgets.QWidget(AutoCal)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox.setObjectName("groupBox")
self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.groupBox)
self.verticalLayout_6.setObjectName("verticalLayout_6")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label = QtWidgets.QLabel(self.groupBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setObjectName("label")
self.horizontalLayout_3.addWidget(self.label)
self.lineEdit = QtWidgets.QLineEdit(self.groupBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
self.lineEdit.setSizePolicy(sizePolicy)
self.lineEdit.setObjectName("lineEdit")
self.horizontalLayout_3.addWidget(self.lineEdit)
self.pushButton = QtWidgets.QPushButton(self.groupBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setObjectName("pushButton")
# self.pushButton.clicked.connect(self.openFileNameDialog )
self.horizontalLayout_3.addWidget(self.pushButton)
self.verticalLayout_6.addLayout(self.horizontalLayout_3)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setObjectName("label_2")
self.horizontalLayout_4.addWidget(self.label_2)
self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.horizontalLayout_4.addWidget(self.lineEdit_2)
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout_4.addWidget(self.pushButton_2)
self.verticalLayout_6.addLayout(self.horizontalLayout_4)
self.verticalLayout.addWidget(self.groupBox)
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_2.setEnabled(True)
self.groupBox_2.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox_2.setObjectName("groupBox_2")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.groupBox_2)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.scrollArea = QtWidgets.QScrollArea(self.groupBox_2)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
self.scrollArea.setSizePolicy(sizePolicy)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.gridLayout = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
# self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 467, 331))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.fillScrollArea()
self.verticalLayout_5.addWidget(self.scrollArea)
self.verticalLayout_3.addWidget(self.groupBox_2)
self.verticalLayout.addLayout(self.verticalLayout_3)
AutoCal.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(AutoCal)
self.menubar.setGeometry(QtCore.QRect(0, 0, 513, 22))
self.menubar.setObjectName("menubar")
self.menuWorkSpace = QtWidgets.QMenu(self.menubar)
self.menuWorkSpace.setObjectName("menuWorkSpace")
self.menuRecipients = QtWidgets.QMenu(self.menubar)
self.menuRecipients.setObjectName("menuRecipients")
AutoCal.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(AutoCal)
self.statusbar.setObjectName("statusbar")
AutoCal.setStatusBar(self.statusbar)
self.menubar.addAction(self.menuWorkSpace.menuAction())
self.menubar.addAction(self.menuRecipients.menuAction())
self.retranslateUi(AutoCal)
QtCore.QMetaObject.connectSlotsByName(AutoCal)
def retranslateUi(self, AutoCal):
_translate = QtCore.QCoreApplication.translate
AutoCal.setWindowTitle(_translate("AutoCal", "AutoCal"))
self.groupBox.setTitle(_translate("AutoCal", "Create New WorkSpace"))
self.label.setText(_translate("AutoCal", "Choose WorkSpace Directory"))
self.pushButton.setText(_translate("AutoCal", "Browse"))
self.label_2.setText(_translate("AutoCal", "WorkSpace Name"))
self.pushButton_2.setText(_translate("AutoCal", "Create"))
self.groupBox_2.setTitle(_translate("AutoCal", "Choose Existing WorkSpace"))
self.menuWorkSpace.setTitle(_translate("AutoCal", "WorkSpace"))
self.menuRecipients.setTitle(_translate("AutoCal", "Recipients"))
def fillScrollArea(self):
for i in range(50):
for j in range(50):
self.gridLayout.addWidget(QtWidgets.QPushButton("Test"), i, j)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
AutoCal = QtWidgets.QMainWindow()
ui = Ui_AutoCal()
ui.setupUi(AutoCal)
AutoCal.show()
sys.exit(app.exec_())
This produces the following scrollArea (ignore the forms):
Current Scroll Area
The main problem is that i need the buttons to always be in the visible section of the scrollArea, whereas as you can see many of them are hidden behind the scrollarea and their text is cut off. I know this is because of the positioning that my function applies to the grid layout but I'm not aware of any other way to position them. I also need the buttons to be dynamic in the sense that if horizontal space becomes greater in a higher row, the ones in the lower row will take up that space. Because of this I dont need horizontal scrolling either, which is why it's disabled.
My issue is now resolved. While flow layout was useful, it was much more intuitive to simply use QListWidget. Many thanks to both eyllanesc and musicamante for their help.
For anyone who has the same issue, the desired result can be achieved by simply creating a QlistWidget and adding items to it:
size = QSize(100,100)
self.listWidget = QListWidget()
size = QtCore.QSize(80,80)
self.listWidget.setResizeMode(QListView.Adjust)
self.listWidget.setIconSize(size)
self.listWidget.itemDoubleClicked.connect(self.itemClicked)
self.listWidget.setViewMode(QListView.IconMode)
I am writing this program to auto save data to Postgres database when QT Text Edit detects the length of string is greater than 5 characters. The program also displaying current date and time.
note: I had created a save button for save the data in QT Text Edit. But actually I need the data to be saved once the QT Text Edit detects the length is more than 5 characters.
I am facing the difficulties as below:
The time displayed is stop, it is called and show when the apps is launched but after that it is just showing static.
the " if len(self.barcode_in) >= 5: " in line 106 is having error.
I did research on Python schedule, but seems like the minimum interval for scanning is 0.5 seconds. Do I need to use threading function to refresh the clock displayed and scan the length of QT Text Edit?
My full code is as below.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'savebarcodedatetime.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
from PyQt5.QtCore import QTime, QTimer
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtWidgets import QApplication, QLCDNumber
import threading
import psycopg2
#from config import config
from threading import Thread
from datetime import *
import time
from time import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(50, 10, 721, 531))
self.widget.setObjectName("widget")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.show_time = QtWidgets.QLCDNumber(self.widget) #LCD = show_time
font = QtGui.QFont()
font.setPointSize(16)
self.show_time.setFont(font)
self.show_time.setObjectName("show_time")
self.horizontalLayout.addWidget(self.show_time)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.show_date = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(16)
self.show_date.setFont(font)
self.show_date.setObjectName("show_date")
self.horizontalLayout.addWidget(self.show_date)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.verticalLayout_2.addLayout(self.horizontalLayout)
spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem3)
self.tableWidget = QtWidgets.QTableWidget(self.widget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.verticalLayout_2.addWidget(self.tableWidget)
spacerItem4 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem4)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.barcode_in = QtWidgets.QTextEdit(self.widget)
self.barcode_in.setObjectName("barcode_in")
self.verticalLayout.addWidget(self.barcode_in)
spacerItem5 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
self.verticalLayout.addItem(spacerItem5)
self.save_button = QtWidgets.QPushButton(self.widget)
font = QtGui.QFont()
font.setPointSize(24)
self.save_button.setFont(font)
self.save_button.setObjectName("save_button")
self.verticalLayout.addWidget(self.save_button)
spacerItem6 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
self.verticalLayout.addItem(spacerItem6)
self.verticalLayout_2.addLayout(self.verticalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.save_button.clicked.connect(self.save_db)
printoutput.printoutmessage()
todaydate = QTime.currentTime()
print(todaydate.toString(Qt.DefaultLocaleLongDate))
todaydate_str = todaydate.toString("H:mm:ss")
self.show_date.setText(todaydate_str)
print(todaydate.toString(Qt.DefaultLocaleLongDate))
if len(self.barcode_in) >= 5:
barcodedata = self.barcode_in.toPlainText()
insertdb.insert_vendor(barcodedata)
print('barcode save')
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.show_date.setText(_translate("MainWindow", "TextLabel"))
self.save_button.setText(_translate("MainWindow", "Save"))
def save_db(self):
print("save")
#mytext = self.textEdit.toPlainText()
barcodedata = self.barcode_in.toPlainText()
insertdb.insert_vendor(barcodedata)
#barcode_in = ''
today = datetime.now()
print (today.strftime(' %a %d-%m-%Y # %H:%M:%S'))
class insertdb:
def insert_vendor(vendor_name):
""" insert a new vendor into the vendors table """
sql = """INSERT INTO vendors(vendor_name)
VALUES(%s) RETURNING vendor_id;"""
conn = None
vendor_id = None
try:
conn = psycopg2.connect(host="192.168.1.104",
port = 5432, database="suppliers",
user="pi", password="1234")
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, (vendor_name,))
# get the generated id back
vendor_id = cur.fetchone()[0]
conn.commit()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
return vendor_id
class printoutput:
def printoutmessage():
print("print output")
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_())
qtextedit can emit signals every time the text on it changes, here is the name and doc.
My suggestion is to connect that signal to you self-defined slot and in the implementation of that method check the length of the new text... is more efficient than polling every "x" seconds for the size of a string.
Now, to the error here:
if len(self.barcode_in) >= 5:
is not valid since
self.barcode_in is actually a widget, you initialized it like doing
self.barcode_in = QtWidgets.QTextEdit(self.widget) therfore makes no sense to compare it against a number, but what you want is to compare the len of the text in that widget, and for this you need the "plain-text" of it (here the doc for that)
I am creating a program that has the function that a checkbox is deleted when it toggled. But when I click the delete button it is not deleted from my scroll area.
I have tried some solutions, but I still have problems on it. An the below code is the best condition I managed until now.
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(300, 495)
MainWindow.setMaximumSize(QtCore.QSize(300, 16777215))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.frame_3 = QtWidgets.QFrame(self.centralwidget)
self.frame_3.setMaximumSize(QtCore.QSize(500, 50))
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 = QtWidgets.QLabel(self.frame_3)
self.label.setObjectName("label")
self.horizontalLayout_2.addWidget(self.label)
self.verticalLayout.addWidget(self.frame_3)
self.frame = QtWidgets.QFrame(self.centralwidget)
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.scrollArea = QtWidgets.QScrollArea(self.frame)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 260, 357))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.frame_4 = QtWidgets.QFrame(self.scrollAreaWidgetContents)
self.frame_4.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_4.setObjectName("frame_4")
self.verticalLayout_3.addWidget(self.frame_4)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout_2.addWidget(self.scrollArea)
self.verticalLayout.addWidget(self.frame)
self.frame_2 = QtWidgets.QFrame(self.centralwidget)
self.frame_2.setMaximumSize(QtCore.QSize(500, 50))
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.pushButton = QtWidgets.QPushButton(self.frame_2)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtWidgets.QPushButton(self.frame_2)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
self.verticalLayout.addWidget(self.frame_2)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtWidgets.QApplication.translate("MainWindow", "MainWindow", None, -1))
self.label.setText(QtWidgets.QApplication.translate("MainWindow", "Chose Number", None, -1))
self.pushButton.setText(QtWidgets.QApplication.translate("MainWindow", "add", None, -1))
self.pushButton_2.setText(QtWidgets.QApplication.translate("MainWindow", "remove", None, -1))
class Remove_checkBox(QtWidgets.QMainWindow,
Ui_MainWindow):
def __init__(self,n):
super(Remove_checkBox, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.checkBox = []
self.fill_comboBox(n)
#Signals
self.ui.pushButton.clicked.connect(lambda: self.add_param())
self.ui.pushButton_2.clicked.connect(lambda: self.remove_param())
def fill_comboBox(self,n):
self.comboBox = QtWidgets.QComboBox(self.ui.frame_3)
self.comboBox.addItem("")
self.comboBox.setItemText(0, QtWidgets.QApplication.translate("MainWindow", "", None, -1))
self.ui.horizontalLayout_2.addWidget(self.comboBox)
for i in range(n):
self.comboBox.addItem("")
self.comboBox.setItemText(i+1, QtWidgets.QApplication.translate("MainWindow", str(i), None, -1))
def add_param(self):
num = self.comboBox.currentText()
self.checkBox.append(QtWidgets.QCheckBox(self.ui.scrollAreaWidgetContents))
self.ui.verticalLayout_3.addWidget(self.checkBox[-1])
self.checkBox[-1].setText(QtWidgets.QApplication.translate("MainWindow", num, None, -1))
self.ui.verticalLayout_3.removeWidget(self.ui.frame_4)
self.ui.verticalLayout_3.addWidget(self.ui.frame_4)
def remove_param(self):
for i in range(len(self.checkBox)):
if self.checkBox[i].isChecked():
self.ui.verticalLayout_3.removeWidget(self.checkBox[i])
self.ui.verticalLayout_3.removeWidget(self.ui.frame_4)
self.ui.verticalLayout_3.addWidget(self.ui.frame_4)
if __name__ == "__main__":
n=10
app = QtWidgets.QApplication.instance()
if app == None:
app = QtWidgets.QApplication([])
myApp = Remove_checkBox(n)
myApp.show()
sys.exit(app.exec_())
It took me a while to find a solution that worked with my issue, but I finally arrived to the solution below presented, based on: What is best way to remove items from layout in pyqt
def remove_element(self, support_layout, element_to_remove, control_list_name):
"""
This function aims to remove selected elements that are contained in a
widget.
Parameters
----------
support_layout : QtWigget Layout
Layout that supports the object that will be removed
element_to_remove : list with QtWidget
A list with Qtwidget items that ones whant to remove.
control_list_name : list with strings
A list with Qtwidget added items string name
Returns
-------
None.
"""
for i in reversed(range(support_layout.count()-1)):
if element_to_remove[i].isChecked():
# Remove checkbox from frame
item = support_layout.takeAt(i)
widget = item.widget()
widget.deleteLater()
# Remove list selected items
control_list_name.remove(element_to_remove[i].text())
element_to_remove.remove(element_to_remove[i])
With this function my problem was solved I am able to follow my project.
# -*- 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();
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_())