Open one QMainWindow from another QMainWindow - python-3.x

I have problem with understanding how to open one QMainWindow from another. I want second window to open when the button in the first window is pressed. But I don't know how to do this because classes of the windows is written in the different way.
When I try just to import Main() class with the second window in the file with first window, second window starts to open when I run the first file and I don't even see the first window
First window:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def openWindow(self):
blank
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(600, 400)
MainWindow.setMinimumSize(QtCore.QSize(600, 400))
MainWindow.setMaximumSize(QtCore.QSize(600, 400))
font = QtGui.QFont()
font.setPointSize(16)
MainWindow.setFont(font)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.splitter = QtWidgets.QSplitter(self.centralwidget)
self.splitter.setGeometry(QtCore.QRect(170, 20, 260, 371))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth())
self.splitter.setSizePolicy(sizePolicy)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.pushButton = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
#self.pushButton.clicked.connect(self.openWindow)
#this is the button by pressing which i want to open second window
self.pushButton_2 = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
self.pushButton_2.setSizePolicy(sizePolicy)
self.pushButton_2.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_4 = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
self.pushButton_4.setSizePolicy(sizePolicy)
self.pushButton_4.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton_4.setFont(font)
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_3 = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
self.pushButton_3.setSizePolicy(sizePolicy)
self.pushButton_3.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Просмотр базы"))
self.pushButton_2.setText(_translate("MainWindow", "Выдача/Принятие книг"))
self.pushButton_4.setText(_translate("MainWindow", "Внести книги в базу"))
self.pushButton_3.setText(_translate("MainWindow", "Редактировать список \nклассов"))
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_())
Second window:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtPrintSupport import *
import sys
import sqlite3
import time
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from test2 import Ui_Dialog
from searchdialog import Ui_Dialogg
from edit import Ui_Dialoge
class Main(QMainWindow):
def __init__(self, *args, **kwargs):
super(Main, self).__init__(*args, **kwargs)
self.conn = sqlite3.connect("booksbase.db")
self.c = self.conn.cursor()
self.c.execute("CREATE TABLE IF NOT EXISTS books(title TEXT,subject TEXT,grade INTEGER,author TEXT,year INTEGER, amount INTEGER)")
self.c.close()
self.setWindowTitle("Books base")
self.setMinimumSize(800, 600)
file_menu = self.menuBar().addMenu("&File")
help_menu = self.menuBar().addMenu("&About")
self.tableWidget = QTableWidget()
self.setCentralWidget(self.tableWidget)
self.tableWidget.setAlternatingRowColors(False)
self.tableWidget.setColumnCount(6)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
self.tableWidget.verticalHeader().setCascadingSectionResizes(True)
self.tableWidget.verticalHeader().setStretchLastSection(False)
header = self.tableWidget.horizontalHeader()
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(6, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
self.tableWidget.setHorizontalHeaderLabels(("Заголовок", "Предмет", "Класс", "Автор","Год", "Колличество"))
self.tableWidget.itemDoubleClicked.connect(self.print)
toolbar = QToolBar()
toolbar.setMovable(False)
self.addToolBar(toolbar)
statusbar = QStatusBar()
self.setStatusBar(statusbar)
btn_ac_adduser = QAction(QIcon("icon/add1.jpg"), "Add Student", self) #add student icon
btn_ac_adduser.triggered.connect(self.insert)
btn_ac_adduser.setStatusTip("Add Student")
toolbar.addAction(btn_ac_adduser)
btn_ac_search = QAction(QIcon("icon/s1.png"), "Search", self) #search icon
btn_ac_search.triggered.connect(self.search)
btn_ac_search.setStatusTip("Search User")
toolbar.addAction(btn_ac_search)
adduser_action = QAction(QIcon("icon/add1.jpg"),"Insert Student", self)
adduser_action.triggered.connect(self.insert)
file_menu.addAction(adduser_action)
searchuser_action = QAction(QIcon("icon/s1.png"), "Search Student", self)
searchuser_action.triggered.connect(self.search)
file_menu.addAction(searchuser_action)
about_action = QAction(QIcon("icon/i1.png"),"Developer", self) #info icon
about_action.triggered.connect(self.about)
help_menu.addAction(about_action)
def loaddata(self):
self.connection = sqlite3.connect("booksbase.db")
query = "SELECT * FROM books"
result = self.connection.execute(query)
self.tableWidget.setRowCount(0)
for row_number, row_data in enumerate(result):
self.tableWidget.insertRow(row_number)
for column_number, data in enumerate(row_data):
self.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(data)))
self.connection.close()
def insert(self):
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.exec_()
print("now")
self.loaddata()
def search(self):
Dialog = QtWidgets.QDialog()
ui = Ui_Dialogg()
ui.setupUi(Dialog)
Dialog.exec_()
def print(self):
row = self.tableWidget.currentRow()
col = self.tableWidget.item(row,0)
title = col.text()
col = self.tableWidget.item(row,1)
subject = col.text()
col = self.tableWidget.item(row,2)
grade = col.text()
col = self.tableWidget.item(row,3)
author = col.text()
col = self.tableWidget.item(row,4)
year = col.text()
col = self.tableWidget.item(row,5)
amount = col.text()
print(title, subject, grade, author, year, amount)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialoge()
ui.setupUi(Dialog, title, subject, grade, author, year, amount)
Dialog.exec_()
self.loaddata()
app = QApplication(sys.argv)
if(QDialog.Accepted == True):
window = Main()
window.show()
window.loaddata()
sys.exit(app.exec_())

The problems resides in the fact that the file you are importing for the second window tries to run its last block:
app = QApplication(sys.argv)
if(QDialog.Accepted == True):
window = Main()
window.show()
window.loaddata()
sys.exit(app.exec_())
When a file (module) is imported, all of its executable statements are processed; in simple terms, everything that's "outside" a def is executed, including the module's own imports, function calls, try/except blocks, for/while loops, and all statements within any class definition.
Since you're checking against QDialog.Accepted (which is a constant), the statement is obviously true, then that if block is executed, resulting in the window being initialized and shown.
Remove that block from the second file and it will work as expected.
Two notes about that code, anyway:
there should exist one and only one QApplication instance for each PyQt based program; the above code could actually crash in most cases because of that;
as said before, QDialog.Accepted is a constant, and it's value is 1, so that if statements doesn't make much sense (it would have been the same as if True == True:); that constant, along with its opposite QDialog.Rejected, is normally used only when checked against the return value of a QDialog.exec() call.

Related

Keeping track of a button status inside a thread (PyQt5)

I created this simple GUI that displays a conuter on a text box. I am using workers and threads (this is just a simplified program I have other threads). I want to be able to check the status of the push button inside the label update thread. for example if the user clicked, then the counter will increment by 5 instead of 1 (for this iteration only), basically I want to keep an eye on this button's status all the time.
here is my code for the counter, how do I add the button check functionality to it?
Edit: I've updated the code using signals and slots to print 'hi' as a start, yet I do not get any output when I run it.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QPoint, QRect, QSize, Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
import os
import cv2
import numpy as np
import time
############################# Telemtry widgets update ##########################
class DISPLAY(QObject):
acc1_val = pyqtSignal(int)
finished = pyqtSignal()
def run(self):
global cntr
cntr = 0
self.inst = Ui_MainWindow()
self.inst.flag.connect(self.update)
print('connected')
while 1:
cntr = cntr +1
time.sleep(1)
self.acc1_val.emit(cntr)
if(cntr > 50):
cntr = 0
self.finished.emit()
#pyqtSlot()
def update(self,flag):
print('hi')
print(flag)
############################ GUI #######################################
class Ui_MainWindow(QObject):
flag = pyqtSignal(int)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(500, 500)
MainWindow.setFocusPolicy(QtCore.Qt.NoFocus)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.Title = QtWidgets.QLabel(self.centralwidget)
self.Title.setGeometry(QtCore.QRect(30, 10, 421, 71))
font = QtGui.QFont()
font.setPointSize(24)
font.setBold(True)
font.setWeight(75)
self.Title.setFont(font)
self.Title.setObjectName("Title")
self.ACC1_X = QtWidgets.QLineEdit(self.centralwidget)
self.ACC1_X.setGeometry(QtCore.QRect(300, 300, 41, 31))
self.ACC1_X.setObjectName("ACC1_X")
self.btn = QtWidgets.QPushButton(self.centralwidget)
self.btn.setGeometry(QtCore.QRect(100, 100, 101, 41))
font = QtGui.QFont()
font.setPointSize(13)
self.btn.setFont(font)
self.btn.setObjectName("Release_btn")
self.btn.clicked.connect(self.release_callback)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1920, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
###################### Display thread ######################
self.thread1 = QThread()
self.worker1 = DISPLAY()
self.worker1.moveToThread(self.thread1)
self.thread1.started.connect(self.worker1.run)
self.worker1.acc1_val.connect(self.Label_update)
self.thread1.finished.connect(self.worker1.deleteLater)
self.thread1.start()
def release_callback(self,flag):
self.x = 1
print(flag)
self.flag.emit(True)
def Label_update(self,acc_val):
self.ACC1_X.setText(str(acc_val))
#print(str(acc_val))
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn.setText(_translate("MainWindow", "click me"))
self.Title.setText(_translate("MainWindow", "TEST"))
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_())

How get text from QTextEdit in Pyqt5? [duplicate]

This question already has an answer here:
Get text from qtextedit and assign it to a variable
(1 answer)
Closed 2 years ago.
I need get text from QTextEdit, but have such trouble: Traceback (most recent call last):
File "main.py", line 28, in otpravit_naz
textboxValue = self.textEdit.text()
AttributeError: 'MyWin' object has no attribute 'textEdit'
This is my code(main.py):
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from test import *
import socket
sock = socket.socket()
class MyWin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.otpravit.clicked.connect(self.otpravit_naz)
def mbox(self, body, title='Error'):
dialog = QMessageBox(QMessageBox.Information, title, body)
dialog.exec_()
def otpravit_naz(self):
print("1")
textboxValue = self.textEdit.text()
print(textboxValue)
#sock.connect(('192.168.1.16', 9090))
sock.connect(("192.168.1.45", 9090))
sock.send(b'textboxValue')
sock.close()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = MyWin()
myapp.show()
sys.exit(app.exec_())
And ui form:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(517, 283)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(60, 20, 421, 201))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(23)
self.verticalLayout.setObjectName("verticalLayout")
self.textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget)
self.textEdit.setObjectName("textEdit")
self.verticalLayout.addWidget(self.textEdit)
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setLineWidth(0)
self.label.setMidLineWidth(0)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.list = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.list.setObjectName("list")
self.list.addItem("")
self.list.addItem("")
self.list.addItem("")
self.verticalLayout.addWidget(self.list)
self.otpravit = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.otpravit.setObjectName("otpravit")
self.verticalLayout.addWidget(self.otpravit)
self.verticalLayout.setStretch(0, 20)
self.verticalLayout.setStretch(1, 20)
self.verticalLayout.setStretch(2, 20)
self.verticalLayout.setStretch(3, 20)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 517, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Предмет:"))
self.list.setItemText(0, _translate("MainWindow", "Русский"))
self.list.setItemText(1, _translate("MainWindow", "Литература"))
self.list.setItemText(2, _translate("MainWindow", "Английский"))
self.otpravit.setText(_translate("MainWindow", "Отправить"))
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_())
If it very stupid troble, pls don't kick me
You're "installing" the GUI on the self.ui object, so every widget that is on the ui is actually accessible as self.ui.someWidget.
Also, QTextEdit doesn't have a text() property, but toPlainText():
def otpravit_naz(self):
print("1")
textboxValue = self.ui.textEdit.toPlainText()
print(textboxValue)
I suggest you to never edit the files generated with pyuic, but always use them as imported modules; read more on using Designer; also, be careful to set the main layout on the central widget, not on its children, and add everything to that layout, otherwise the children widgets could be hidden whenever the window is resized.

Pyqt5 QFileDialog not working in my program for Getting Directories

I have This Qt MainWindow Shown Below:
I want my Browse button to Open a Dialog box for selecting Specific Directory.
I Went through the various post on Stack Overflow, I tried implementing the solution in the post, but It's not working for me.
Here is my Code :
from PyQt5 import QtCore, QtGui, QtWidgets
import os
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.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setObjectName("gridLayout_2")
self.start_button = QtWidgets.QPushButton(self.centralwidget)
self.start_button.setAutoFillBackground(False)
self.start_button.setAutoDefault(False)
self.start_button.setDefault(False)
self.start_button.setFlat(False)
self.start_button.setObjectName("start_button")
self.start_button.clicked.connect(lambda: self.start_button_click())
self.gridLayout_2.addWidget(self.start_button, 0, 0, 1, 1)
self.Br_button = QtWidgets.QPushButton(self.centralwidget)
self.Br_button.setObjectName("Br_button")
self.Br_button.clicked.connect(lambda: self.browse_button())
self.gridLayout_2.addWidget(self.Br_button, 2, 0, 1, 1)
self.label = QtWidgets.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 2, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.gridLayout_2.addWidget(self.tableWidget, 3, 0, 1, 2)
self.gridLayout.addLayout(self.gridLayout_2, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.start_button.setToolTip(_translate("MainWindow", "Start The Program"))
self.start_button.setText(_translate("MainWindow", "Start"))
self.Br_button.setToolTip(_translate("MainWindow", "Browse the File Location to Watch on"))
self.Br_button.setText(_translate("MainWindow", "Browse"))
def start_button_click(self):
self.label.setText("Hello")
def browse_button(self):
fileName = QtWidgets.QFileDialog.getExistingDirectory(QtWidgets.QFileDialog,None,"Open Directory",os.getcwd(), QtWidgets.QFileDialog.ShowDirsOnly)
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_())
When I Click on the Browse button it closes the Application abruptly after few seconds and I am Getting This Error Shown below:
Try it:
import sys
import os
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Form(QMainWindow):
def __init__(self,parent=None):
super().__init__(parent)
self.plainTextEdit = QPlainTextEdit()
self.plainTextEdit.setFont(QFont('Arial', 11))
openDirButton = QPushButton("Open Directory")
openDirButton.clicked.connect(self.browse_button)
layoutV = QVBoxLayout()
layoutV.addWidget(openDirButton)
layoutH = QHBoxLayout()
layoutH.addLayout(layoutV)
layoutH.addWidget(self.plainTextEdit)
centerWidget = QWidget()
centerWidget.setLayout(layoutH)
self.setCentralWidget(centerWidget)
def browse_button(self):
fileName = QFileDialog.getExistingDirectory(
#QtWidgets.QFileDialog, # ???
None,
"Open Directory",
os.getcwd(),
QFileDialog.ShowDirsOnly)
self.plainTextEdit.appendHtml("<br>Chose a folder: <b>{}</b>".format(fileName))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Form()
ex.resize(740,480)
ex.setWindowTitle("PyQt5-QFileDialog")
ex.show()
sys.exit(app.exec_())

Display Sensor Output on QLCDNumber using PyQT5

So I have developed a code which will detect a voltage off a transducer and then output an average voltage, my question here is how can I get this value to update as my sensor value changes, currently it is prinitng the initial value and then not updating, I created a mainwindow using QTDesigner, and I am using Python3 and PyQt5 library to write the code.
is this even possible? if so how?
This is my code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap
import RPi.GPIO as GPIO
import Test_rc
import time
import board
import busio
from adafruit_ads1x15.single_ended import ADS1115
i2c = busio.I2C(board.SCL,board.SDA)
adc = ADS1115(i2c)
GAIN = 2/3
c1 = 525.4
c2=28152
GPIO.setmode(GPIO.BCM)
Relay_1 = 27
Transducer = 17
GPIO.setup(Transducer,GPIO.IN)
GPIO.setup(Relay_1, GPIO.OUT)
GPIO.output(Relay_1, GPIO.HIGH)
GPIO.output(Relay_1, GPIO.LOW)
def Pressure_Reading():
while True:
time.sleep(0.02)
r0 = adc.read_volts(0,gain = GAIN, data_rate=None)
r1 = adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts = r0*94.72436287
Pressure_adc = r1*(c1/c2)
time.sleep(0.02)
r01= adc.read_volts(0,gain = GAIN, data_rate=None)
r11= adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts2 = r01*94.72436287
Pressure_adc2 = r11*(c1/c2)
time.sleep(0.02)
r02= adc.read_volts(0,gain = GAIN, data_rate=None)
r12= adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts3 = r02*94.72436287
Pressure_adc3 = r12*(c1/c2)
time.sleep(0.02)
r03 = adc.read_volts(0,gain = GAIN, data_rate=None)
r13 = adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts4 = r03*94.72436287
Pressure_adc4 = r13*(c1/c2)
time.sleep(0.02)
r04= adc.read_volts(0,gain = GAIN, data_rate=None)
r14= adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts5 = r04*94.72436287
Pressure_adc5 = r14*(c1/c2)
Pressure_Volts_Avg = (Pressure_Volts+Pressure_Volts2+Pressure_Volts3+Pressure_Volts4+Pressure_Volts5)/5
Pressure_adc_Avg = (Pressure_adc+Pressure_adc2+Pressure_adc3+Pressure_adc4+Pressure_adc5)/5
Pressure_Avg = (Pressure_Volts_Avg+Pressure_adc_Avg)/2
return Pressure_Avg
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(788, 424)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.stackedWidget = QtWidgets.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(10, 0, 761, 501))
self.stackedWidget.setObjectName("stackedWidget")
self.page_3 = QtWidgets.QWidget()
self.page_3.setObjectName("page_3")
self.label = QtWidgets.QLabel(self.page_3)
self.label.setGeometry(QtCore.QRect(200, 0, 341, 61))
font = QtGui.QFont()
font.setFamily("Arial Black")
font.setPointSize(22)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.pushButton_2 = QtWidgets.QPushButton(self.page_3)
self.pushButton_2.setGeometry(QtCore.QRect(220, 170, 141, 41))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton = QtWidgets.QPushButton(self.page_3)
self.pushButton.setGeometry(QtCore.QRect(380, 170, 141, 41))
self.pushButton.setObjectName("pushButton")
self.label_2 = QtWidgets.QLabel(self.page_3)
self.label_2.setGeometry(QtCore.QRect(120, 260, 541, 141))
self.label_2.setObjectName("label_2")
self.groupBox_2 = QtWidgets.QGroupBox(self.page_3)
self.groupBox_2.setGeometry(QtCore.QRect(90, 40, 101, 221))
self.groupBox_2.setTitle("")
self.groupBox_2.setObjectName("groupBox_2")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.groupBox_2)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.label_7 = QtWidgets.QLabel(self.groupBox_2)
self.label_7.setObjectName("label_7")
self.verticalLayout_2.addWidget(self.label_7)
self.lcdNumber = QtWidgets.QLCDNumber(self.groupBox_2)
self.lcdNumber.setObjectName("lcdNumber")
self.verticalLayout_2.addWidget(self.lcdNumber)
self.lcdNumber.display(Pressure_Reading())
I've input all the code up until the lcdnumber calling.
The rest of the code after the mainwindow class, I have my code control a relay and push buttons navigate a few pages, this part of the code runs fine
class ControlMainWindow(QtWidgets.QMainWindow):
def __init__(self,parent=None):
super(ControlMainWindow,self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.SettingsButton.clicked.connect(lambda:self.ui.stackedWidget.setCurrentIndex(1))
self.ui.pushButton_5.clicked.connect(lambda:self.ui.stackedWidget.setCurrentIndex(0))
self.ui.pushButton.clicked.connect(self.OnSwitch)
self.ui.pushButton_2.clicked.connect(self.OffSwitch)
self.ui.DelayButton.clicked.connect(self.Delay_Switch)
def OnSwitch(self):
GPIO.output(Relay_1, GPIO.HIGH)
def OffSwitch(self):
GPIO.output(Relay_1, GPIO.LOW)
def Delay_Switch(self):
time.sleep(5)
GPIO.output(Relay_1,GPIO.HIGH)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
Sorry. I'm not familiar with some of the modules that you use.
In general, it might look like this:
main.py
import sys
from random import randint
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer
from ui import Ui_MainWindow
class Form(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.i = 0
self.voltageMin = 180
self.voltageMax = 180
self.ui.lcdNumberCur.display(self.i)
self.ui.pushButton.clicked.connect(self.startTimer)
self.timer = QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.updateData)
self.show()
def startTimer(self):
if self.ui.pushButton.text() == "Start Timer":
self.timer.start(1000)
self.ui.pushButton.setText("Stop Timer")
else:
self.ui.pushButton.setText("Start Timer")
self.timer.stop()
def updateData(self):
voltage = randint(90, 260) # <--- insert your average voltage here
self.ui.lcdNumberCur.display(voltage)
if voltage > self.voltageMax:
self.voltageMax = voltage
self.ui.lcdNumberMax.display(self.voltageMax)
elif voltage < self.voltageMin:
self.voltageMin = voltage
self.ui.lcdNumberMin.display(self.voltageMin)
if __name__ == '__main__':
app = QApplication(sys.argv)
frm = Form()
sys.exit(app.exec_())
ui.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(500, 300)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(0, 0, 400, 200))
self.groupBox.setObjectName("groupBox")
self.lcdNumberMax = QtWidgets.QLCDNumber(self.groupBox)
self.lcdNumberMax.setGeometry(QtCore.QRect(225, 10, 151, 41))
self.lcdNumberMax.setObjectName("lcdNumberMax")
self.lcdNumberCur = QtWidgets.QLCDNumber(self.groupBox)
self.lcdNumberCur.setGeometry(QtCore.QRect(225, 55, 151, 41))
self.lcdNumberCur.setObjectName("lcdNumberCur")
self.lcdNumberMin = QtWidgets.QLCDNumber(self.groupBox)
self.lcdNumberMin.setGeometry(QtCore.QRect(225, 100, 151, 41))
self.lcdNumberMin.setObjectName("lcdNumberMin")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(20, 50, 150, 50))
self.label.setObjectName("label")
self.labelMax = QtWidgets.QLabel(self.groupBox)
self.labelMax.setGeometry(QtCore.QRect(20, 8, 150, 50))
self.labelMax.setObjectName("labelMax")
self.labelMin = QtWidgets.QLabel(self.groupBox)
self.labelMin.setGeometry(QtCore.QRect(20, 95, 150, 50))
self.labelMin.setObjectName("labelMin")
self.pushButton = QtWidgets.QPushButton("pushButton", self.groupBox) #(self.scrollAreaWidgetContents)
self.pushButton.setGeometry(QtCore.QRect(180, 165, 75, 23))
self.pushButton.setObjectName("pushButton")
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", "LCDNumber - Timer(Start-Stop)"))
self.groupBox.setTitle(_translate("MainWindow", "Data"))
self.label.setText(_translate("MainWindow", "Current voltage in the network"))
self.labelMin.setText(_translate("MainWindow", "Min voltage in the network"))
self.labelMax.setText(_translate("MainWindow", "Max voltage in the network"))
self.pushButton.setText(_translate("MainWindow", "Start Timer"))
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_())
Ok, so getting caught up in all the gui stuff, I had to implement threading and remove the functions from within the gui thread. Because the question regarded the output of the sensor I removed all the code irrelevant to it and included just the code required for the Sensor.. I hope this makes sense.
This resolved the issue:
class Worker(QtCore.QThread):
valueFound = QtCore.pyqtSignal(int, name="valueFound")
GAIN = 2/3
c1 = 525.4
c2=28152
Relay_1 = 27
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
self.runFlag = False
self.i2c = busio.I2C(board.SCL,board.SDA)
self.adc = ADS1115(self.i2c)
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.Relay_1, GPIO.OUT)
GPIO.output(self.Relay_1, GPIO.HIGH)
GPIO.output(self.Relay_1, GPIO.LOW)
def startThread(self):
self.runFlag = True
self.start()
def stopThread(self):
self.runFlag = False
def run(self):
while self.runFlag:
self.valueFound.emit(self.Pressure_Reading())
......
def run(self):
while self.runFlag:
self.valueFound.emit(self.Pressure_Reading())
.....
self.worker = Worker(self)
self.worker.valueFound.connect(self.OnValueFound)
.....
self.worker.startThread()
def closeEvent(self, event):
self.worker.stopThread()
while self.worker.isRunning():
pass
event.accept()
def OnValueFound(self, value):
self.ui.lcdNumber.display(value)
The addition of these allowed the program to continuously update the LCD Number.

How to send a signal from a QDialog to a QMainWindow class

I have made a UI which includes a mainwindow and a button that opens a dialog window. I want to send the current text changed signal from a line edit in the dialog window to the Mainwindow class as a variable. An example of the code I am making is below:
from PyQt5 import QtCore, QtGui, QtWidgets
from selenium import webdriver
import time
import threading
from bs4 import BeautifulSoup as soup
import requests
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(388, 179)
self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
self.lineEdit_2.setGeometry(QtCore.QRect(100, 100, 271, 21))
font = QtGui.QFont()
font.setFamily("Yu Gothic")
self.lineEdit_2.setFont(font)
self.lineEdit_2.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);")
self.lineEdit_2.setObjectName("lineEdit_2")
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
# self.pushButton.pressed.connect(self.textEdit.clear)
# self.pushButton.pressed.connect(self.sejd)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.keyworddict = {}
self.count = {}
MainWindow.setObjectName("MainWindow")
MainWindow.resize(803, 538)
MainWindow.setMinimumSize(QtCore.QSize(0, 0))
MainWindow.setMaximumSize(QtCore.QSize(10000, 10000))
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.pushButton = QtWidgets.QPushButton(self.centralWidget)
self.pushButton.setGeometry(QtCore.QRect(180, 210, 75, 23))
font = QtGui.QFont()
font.setFamily("Yu Gothic")
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralWidget)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pushButton.pressed.connect(self.on_Button_clicked)
def on_Button_clicked(self):
dialog = QtWidgets.QDialog()
dialog.ui = Ui_Dialog()
dialog.ui.setupUi(dialog)
dialog.setWindowTitle("Login")
dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
dialog.exec_()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.setWindowTitle("ui")
w.show()
sys.exit(app.exec_())
All help appreciated. I would preferably like an example using the code above.
There are at least two simple ways to do this. You can either connect a signal when the dialog is created, or just retrieve the text after the dialog closes:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
...
def dialogTextChanged(self, text):
print(text)
def on_Button_clicked(self):
dialog = QtWidgets.QDialog()
dialog.ui = Ui_Dialog()
dialog.ui.setupUi(dialog)
# connect signal to slot
dialog.ui.lineEdit_2.textChanged.connect(self.dialogTextChanged)
dialog.setWindowTitle("Login")
# this is not needed
# dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
dialog.exec_()
# or retrieve text after dialog closes
print(dialog.ui.lineEdit_2.text())
dialog.deleteLater()
If this is a login dialog, you should probably have an accept button which is connected to the dialog's accept() slot. Then you can check the exit status of the dialog like this:
if dialog.exec_() == QtWidgets.QDialog.Accepted:
text = dialog.ui.lineEdit_2.text()
# do sothing with text ...
dialog.deleteLater()

Resources