im pretty new to working with pyqt5 in python, everything is kinda running how it is supposed to be. the only issue i have is that when im triggering to start the function stepperaction(self, index) with the "START" button, i can see the code running in the console, but the UI crashes while the code is running if i click anywhere on the ui with my mouse. i would like to be able to press the "STOP" button in the UI even while the function is running. How am i able to fix this?
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.13.0
import time
import sys
# import RPi.GPIO as GPIO
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QVariant
stepcount = 0
class Ui_mainWindow(object):
def setupUi(self, mainWindow):
mainWindow.setObjectName("mainWindow")
mainWindow.resize(557, 320)
self.centralwidget = QtWidgets.QWidget(mainWindow)
self.centralwidget.setEnabled(True)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(360, 40, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(360, 70, 75, 23))
self.pushButton_4.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(270, 70, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(150, 40, 101, 22))
self.comboBox.setEditable(False)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("", QVariant(10*1600))
self.comboBox.addItem("", QVariant(20))
self.comboBox.addItem("", QVariant(30))
self.comboBox.addItem("", QVariant(40))
self.comboBox.addItem("", QVariant(50))
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 30, 121, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName("label")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(20, 250, 118, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(270, 40, 75, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(400, 252, 71, 21))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(480, 252, 51, 21))
self.label_3.setObjectName("label_3")
mainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(mainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 557, 21))
self.menubar.setObjectName("menubar")
self.menuSmart_Spray_Booth_Configuration = QtWidgets.QMenu(self.menubar)
self.menuSmart_Spray_Booth_Configuration.setObjectName("menuSmart_Spray_Booth_Configuration")
mainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(mainWindow)
self.statusbar.setObjectName("statusbar")
mainWindow.setStatusBar(self.statusbar)
self.menubar.addAction(self.menuSmart_Spray_Booth_Configuration.menuAction())
self.retranslateUi(mainWindow)
QtCore.QMetaObject.connectSlotsByName(mainWindow)
self.comboBox.activated.connect(self.handleactivated)
self.pushButton.clicked.connect(lambda: self.stepperaction(index=self.comboBox.currentIndex()))
self.pushButton_2.clicked.connect(lambda: self.stop())
def handleactivated(self, index):
print(self.comboBox.itemText(index), "handle")
print(self.comboBox.itemData(index), "handle")
self.label_3.setText(self.comboBox.itemText(index))
def retranslateUi(self, mainWindow):
_translate = QtCore.QCoreApplication.translate
mainWindow.setWindowTitle(_translate("mainWindow", "Smart Spray Booth - Configuration"))
self.pushButton.setText(_translate("mainWindow", "START"))
self.pushButton_2.setText(_translate("mainWindow", "STOP"))
self.pushButton_3.setText(_translate("mainWindow", "Nullpunkt"))
self.comboBox.setItemText(0, _translate("mainWindow", "5cm"))
self.comboBox.setItemText(1, _translate("mainWindow", "10cm"))
self.comboBox.setItemText(2, _translate("mainWindow", "15cm"))
self.comboBox.setItemText(3, _translate("mainWindow", "20cm"))
self.comboBox.setItemText(4, _translate("mainWindow", "25cm"))
self.label.setText(_translate("mainWindow", "Bauteilgröße:"))
self.label_2.setText(_translate("mainWindow", "Bauteilgröße:"))
self.label_3.setText(_translate("mainWindow", "0 cm"))
self.menuSmart_Spray_Booth_Configuration.setTitle(_translate("mainWindow", "Smart Spray Booth - Configuration"))
if self.comboBox.currentTextChanged:
print(self.comboBox.currentData(), "from if")
def stop(self):
print("programm wird beendet")
sys.exit()
def stepperaction(self, index):
# GPIO.setmode(GPIO.BOARD) # read the pin as board instead of BCM pin
global stepcount
stepcount = self.comboBox.itemData(index)
print(stepcount, "this is given step")
# return stepcount
FastSpeed = 0.0001 # old = 0.001 Change this depends on your stepper motor
LowSpeed = 0.0001 # old = 0.001 Change this depends on your stepper motor
counter = 0
countery = 0
while True and counter < 3:
print("Move Up", stepcount, "steps")
for i in range(stepcount):
countery = countery + 1
print(countery)
time.sleep(LowSpeed)
print(countery)
time.sleep(LowSpeed)
time.sleep(1)
print("Move Down", stepcount, "steps")
for i in range(stepcount):
countery = countery + 1
print(countery)
time.sleep(FastSpeed)
print(countery)
time.sleep(FastSpeed)
time.sleep(1)
counter += 1
print("success")
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_())
I can't test on PyQt5, but on PySide you just need to pass the name of the function to connect, not execute it. It might also be better to avoid using lambdas in QT slots.
Try this modification:
....
self.pushButton.clicked.connect(self.stepperaction)
....
def stepperaction(self, index=None):
if index is None:
index = self.comboBox.currentIndex()
# GPIO.setmode(GPIO.BOARD) # read the pin as board instead of BCM pin
global stepcount
....
Related
I created a back button in new window and next button in main window. After I clicked the next button to show a new window, it was successfully hides the current main window but when I clicked back button on the new window, the application automatically closes itself. Any idea?
The code in first mainWindow.py file:
from PyQt5 import QtCore, QtGui, QtWidgets
try:
from secondWindow import Ui_SecondWindow
except:
import secondWindow
class Ui_firstWindow(object):
def secondWindow(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_SecondWindow()
self.ui.setupUi(self.window)
self.window.show()
if self.window.show():
self.hide
def setupUi(self, firstWindow):
firstWindow.setObjectName("firstWindow")
firstWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(firstWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_next = QtWidgets.QPushButton(self.centralwidget)
self.btn_next.setGeometry(QtCore.QRect(160, 100, 521, 291))
self.btn_next.setObjectName("btn_next")
######To Open second window###########
self.btn_next.clicked.connect(self.secondWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 420, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
firstWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(firstWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
firstWindow.setMenuBar(self.menubar)
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.btn_next.setText(_translate("firstWindow", "Next"))
self.label.setText(_translate("firstWindow", "First Window"))
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_())
The codes in second secondWindow.py file:
from PyQt5 import QtCore, QtGui, QtWidgets
try:
from mainWindow import Ui_firstWindow
except:
import mainWindow
class Ui_SecondWindow(object):
###function to go back the first window######
# #pyqtSlot()
def openBackFirstWindow(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_firstWindow()
self.ui.setupUi(self.window)
self.window.show()
if self.window.show():
self.hide
def setupUi(self, SecondWindow):
SecondWindow.setObjectName("SecondWindow")
SecondWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_back = QtWidgets.QPushButton(self.centralwidget)
self.btn_back.setGeometry(QtCore.QRect(220, 100, 401, 281))
self.btn_back.setObjectName("btn_back")
###To go back to first windo######
self.btn_back.clicked.connect(self.openBackFirstWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(370, 440, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
SecondWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(SecondWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
SecondWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(SecondWindow)
self.statusbar.setObjectName("statusbar")
SecondWindow.setStatusBar(self.statusbar)
self.retranslateUi(SecondWindow)
QtCore.QMetaObject.connectSlotsByName(SecondWindow)
def retranslateUi(self, SecondWindow):
_translate = QtCore.QCoreApplication.translate
SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
self.btn_back.setText(_translate("SecondWindow", "Back"))
self.label.setText(_translate("SecondWindow", "Second Window"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
SecondWindow = QtWidgets.QMainWindow()
ui = Ui_SecondWindow()
ui.setupUi(SecondWindow)
SecondWindow.show()
sys.exit(app.exec_())
When i clicked the back button in second window, the application stopped working and exits itself. Any idea?
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.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_firstWindow(object):
def setupUi(self, firstWindow):
firstWindow.setObjectName("firstWindow")
firstWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(firstWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_next = QtWidgets.QPushButton(self.centralwidget)
self.btn_next.setGeometry(QtCore.QRect(160, 100, 521, 291))
self.btn_next.setObjectName("btn_next")
# ######To Open second window###########
# self.btn_next.clicked.connect(self.secondWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 420, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
firstWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(firstWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
firstWindow.setMenuBar(self.menubar)
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.btn_next.setText(_translate("firstWindow", "Next"))
self.label.setText(_translate("firstWindow", "First Window"))
class Ui_SecondWindow(object):
def setupUi(self, SecondWindow):
SecondWindow.setObjectName("SecondWindow")
SecondWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_back = QtWidgets.QPushButton(self.centralwidget)
self.btn_back.setGeometry(QtCore.QRect(220, 100, 401, 281))
self.btn_back.setObjectName("btn_back")
# ###To go back to first windo######
# self.btn_back.clicked.connect(self.openBackFirstWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(370, 440, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
SecondWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(SecondWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
SecondWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(SecondWindow)
self.statusbar.setObjectName("statusbar")
SecondWindow.setStatusBar(self.statusbar)
self.retranslateUi(SecondWindow)
QtCore.QMetaObject.connectSlotsByName(SecondWindow)
def retranslateUi(self, SecondWindow):
_translate = QtCore.QCoreApplication.translate
SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
self.btn_back.setText(_translate("SecondWindow", "Back"))
self.label.setText(_translate("SecondWindow", "Second Window"))
class SecondWindow(QtWidgets.QMainWindow, Ui_SecondWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
class MainWindow(QtWidgets.QMainWindow, Ui_firstWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
######To Open second window###########
self.btn_next.clicked.connect(self.secondWindow)
def secondWindow(self):
self.window = SecondWindow()
###To go back to first windo######
self.window.btn_back.clicked.connect(self.openBackFirstWindow)
self.window.show()
self.hide()
###function to go back the first window######
def openBackFirstWindow(self):
self.show()
self.window.hide()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
firstWindow = MainWindow()
firstWindow.show()
sys.exit(app.exec_())
This is the Code i am trying below.
I want to play .avi, .mp4, etc.
I am able to select video but unable to play.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.mediaPlayer = QtMultimedia.QMediaPlayer(None, QtMultimedia.QMediaPlayer.VideoSurface)
videoWidget = QtMultimediaWidgets.QVideoWidget()
MainWindow.setObjectName("MainWindow")
MainWindow.resize(881, 578)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.gridLayout_2 = QtWidgets.QGridLayout(self.frame)
self.gridLayout_2.setObjectName("gridLayout_2")
self.widget = QVideoWidget(self.frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
self.widget.setSizePolicy(sizePolicy)
self.widget.setMinimumSize(QtCore.QSize(711, 471))
self.widget.setMaximumSize(QtCore.QSize(711, 471))
self.widget.setObjectName("widget")
self.gridLayout_2.addWidget(self.widget, 0, 0, 3, 1)
self.audiobar = QtWidgets.QSlider(self.frame)
self.audiobar.setMinimumSize(QtCore.QSize(22, 160))
self.audiobar.setMaximumSize(QtCore.QSize(22, 160))
self.audiobar.setOrientation(QtCore.Qt.Vertical)
self.audiobar.setObjectName("audiobar")
self.gridLayout_2.addWidget(self.audiobar, 2, 2, 1, 1)
self.videobar = QtWidgets.QSlider(self.frame)
self.videobar.setMinimumSize(QtCore.QSize(711, 22))
self.videobar.setMaximumSize(QtCore.QSize(711, 22))
self.videobar.setOrientation(QtCore.Qt.Horizontal)
self.videobar.setObjectName("videobar")
self.gridLayout_2.addWidget(self.videobar, 3, 0, 1, 1)
self.frame_2 = QtWidgets.QFrame(self.frame)
self.frame_2.setMinimumSize(QtCore.QSize(120, 111))
self.frame_2.setMaximumSize(QtCore.QSize(120, 111))
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.playbtn = QtWidgets.QPushButton(self.frame_2)
self.playbtn.setGeometry(QtCore.QRect(20, 10, 75, 23))
self.playbtn.setObjectName("playbtn")
self.playbtn.setEnabled(False)
self.pausebtn = QtWidgets.QPushButton(self.frame_2)
self.pausebtn.setGeometry(QtCore.QRect(20, 40, 75, 23))
self.pausebtn.setObjectName("pausebtn")
self.stopbtn = QtWidgets.QPushButton(self.frame_2)
self.stopbtn.setGeometry(QtCore.QRect(20, 70, 75, 23))
self.stopbtn.setObjectName("stopbtn")
self.gridLayout_2.addWidget(self.frame_2, 0, 2, 1, 1)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem, 0, 1, 1, 1)
self.gridLayout.addWidget(self.frame, 1, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 881, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen = QtWidgets.QAction(MainWindow)
self.actionOpen.setObjectName("actionOpen")
self.actionClose = QtWidgets.QAction(MainWindow)
self.actionClose.setObjectName("actionClose")
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionClose)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.mediaPlayer.setVideoOutput(videoWidget)
self.actionOpen.triggered.connect(self.openFile)
self.playbtn.clicked.connect(self.play)
self.mediaPlayer.setVideoOutput(videoWidget)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MPlayer"))
self.playbtn.setText(_translate("MainWindow", "Play"))
self.pausebtn.setText(_translate("MainWindow", "Pause"))
self.stopbtn.setText(_translate("MainWindow", "Stop"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen.setText(_translate("MainWindow", "Open"))
self.actionClose.setText(_translate("MainWindow", "Close"))
def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(None, "Select Video", " ", "Video Files (*.mp4 *.avi)",
QtCore.QDir.homePath())
if fileName != '':
self.mediaPlayer.setMedia(
QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(fileName)))
self.playbtn.setEnabled(True)
self.statusbar.showMessage(fileName)
self.play()
def play(self):
if self.mediaPlayer.state() == QtMultimedia.QMediaPlayer.PlayingState:
self.mediaPlayer.pause()
else:
self.mediaPlayer.play()
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 set the video output to videoWidget, but you didn't add it to the interface.
You already created a video widget, though, and it is self.widget, so you just have to use that (and only once):
self.mediaPlayer.setVideoOutput(self.widget)
Note that you are using the output of pyuic for your program, which is highly discouraged. Follow the guidelines about using Designer instead.
This question already has answers here:
argument 1 has unexpected type 'Ui_mainWindow'
(4 answers)
Closed 3 years ago.
def openFileNameDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
if fileName:
print(fileName)
For this code, this is my output ,
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files ();;Python Files (.py)", options=options)
TypeError: getOpenFileName(parent: QWidget = None, caption: str = '', directory: str = '', filter: str = '', initialFilter: str = '', options: Union[QFileDialog.Options, QFileDialog.Option] = 0): argument 1 has unexpected type 'Ui_MainWindow'
How do I fix this ?
(Post Edit) :
This is my GUI code :
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(443, 427)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(350, 100, 75, 23))
self.pushButton.setObjectName("pushButton")
**self.pushButton.clicked.connect(self.openFileNameDialog)**
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(40, 100, 281, 21))
self.lineEdit.setObjectName("lineEdit")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 443, 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.pushButton.setText(_translate("MainWindow", "Browse"))
The error is thrown when I run the python script.
Thanks for providing the GUI code. I believe the error most likely arises from inheritance complications. I am not sure why you are passing a separate MainWindow object to various functions. Instead, try to inherit from QMainWindow() and assign all the UI elements to self.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setObjectName("MainWindow")
self.resize(443, 427)
self.centralwidget = QWidget(self)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QPushButton(self.centralwidget)
self.pushButton.setGeometry(QRect(350, 100, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.openFileNameDialog)
self.lineEdit = QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QRect(40, 100, 281, 21))
self.lineEdit.setObjectName("lineEdit")
self.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(self)
self.menubar.setGeometry(QRect(0, 0, 443, 21))
self.menubar.setObjectName("menubar")
self.setMenuBar(self.menubar)
self.statusbar = QStatusBar(self)
self.statusbar.setObjectName("statusbar")
self.setStatusBar(self.statusbar)
self.retranslateUi()
QMetaObject.connectSlotsByName(self)
def retranslateUi(self):
_translate = QCoreApplication.translate
self.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Browse"))
def openFileNameDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
if fileName:
print(fileName)
if __name__ == '__main__':
app = QApplication(sys.argv)
MW = MainWindow()
MW.show()
sys.exit(app.exec_())
I'm developing a web browser in Python and PyQt5. The browser is working fine but new tab and javascript window.open() is not working. I want to know how to enable new tab and popup functions. javascript alert() function is working but new window and new tab is not working.
If you could help me then I'll be very thankful to you.
from PyQt5 import QtCore, QtGui, QtWidgets # +++ QtWidgets
from PyQt5 import QtWebEngineWidgets
from PyQt5.QtWebEngineWidgets import QWebEnginePage,QWebEngineSettings
class Ui_MainWindow(object):
def back(self): self.webView.back()
def forword(self): self.webView.forward()
def reload(self): self.webView.reload()
def stop(self): self.webView.stop()
def newtab(self): self.QWebEnginePage.OpenLinkInNewTab()
def createWindow(self, windowType):
if windowType == QWebEnginePage.WebBrowserTab:
self.webView = Ui_MainWindow()
self.webView.setAttribute(Qt.WA_DeleteOnClose, True)
self.webView.show()
return self.webView
return super(Ui_MainWindow, self).createWindow(windowType)
def home(self):
self.webView.load(QtCore.QUrl("http://pyxisad.com"))
QWebEnginePage.JavascriptCanOpenWindows:True
def search(self):
url = self.ln_addressbar.text()
self.webView.load(QtCore.QUrl(url))
QWebEnginePage.JavascriptCanOpenWindows:True
def setupUi(self, MainWindow):
MainWindow.setObjectName("PyxisAd")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tb_back = QtWidgets.QToolButton(self.centralwidget)
self.tb_back.setGeometry(QtCore.QRect(10, 20, 41, 31))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("icons/back.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.tb_back.setIcon(icon)
self.tb_back.setIconSize(QtCore.QSize(32, 32))
self.tb_back.setObjectName("tb_back")
############### Event #############################
self.tb_back.clicked.connect(self.back)
##################################################
self.tb_reload = QtWidgets.QToolButton(self.centralwidget)
self.tb_reload.setGeometry(QtCore.QRect(60, 20, 41, 31))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("icons/reload.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.tb_reload.setIcon(icon1)
self.tb_reload.setIconSize(QtCore.QSize(32, 32))
self.tb_reload.setObjectName("tb_reload")
############### Event #############################3
self.tb_reload.clicked.connect(self.reload)
##################################################
self.tb_forword_2 = QtWidgets.QToolButton(self.centralwidget)
self.tb_forword_2.setGeometry(QtCore.QRect(110, 20, 41, 31))
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("icons/forword.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.tb_forword_2.setIcon(icon2)
self.tb_forword_2.setIconSize(QtCore.QSize(32, 32))
self.tb_forword_2.setObjectName("tb_forword_2")
############### Event #############################3
self.tb_forword_2.clicked.connect(self.forword)
##################################################
self.tb_home = QtWidgets.QToolButton(self.centralwidget)
self.tb_home.setGeometry(QtCore.QRect(160, 20, 41, 31))
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap("icons/home.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.tb_home.setIcon(icon3)
self.tb_home.setIconSize(QtCore.QSize(32, 32))
self.tb_home.setObjectName("tb_home")
############### Event #############################3
self.tb_home.clicked.connect(self.home)
##################################################
self.ln_addressbar = QtWidgets.QLineEdit(self.centralwidget)
self.ln_addressbar.setGeometry(QtCore.QRect(210, 20, 491, 31))
self.ln_addressbar.setObjectName("ln_addressbar")
self.ln_addressbar.setPlaceholderText("Enter URL..")
self.tb_search = QtWidgets.QToolButton(self.centralwidget)
self.tb_search.setGeometry(QtCore.QRect(710, 20, 41, 31))
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap("icons/search.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.tb_search.setIcon(icon4)
self.tb_search.setIconSize(QtCore.QSize(32, 32))
self.tb_search.setObjectName("tb_search")
############### Event #############################3
self.tb_search.clicked.connect(self.search)
#self.tb_search.returnPressed.connect(self.search)
##################################################
self.webView = QtWebEngineWidgets.QWebEngineView(self.centralwidget) # + QWebEngineView
self.webView.setGeometry(QtCore.QRect(0, 60, 1400, 700))
self.webView.setUrl(QtCore.QUrl("about:blank"))
self.webView.setObjectName("webView")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
############### Event #############################
#self.newtab.clicked.connect(createWindow())
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("PyxisAd", "PyxisAd"))
self.tb_back.setText(_translate("PyxisAd", "back"))
self.tb_reload.setText(_translate("PyxisAd", "reload"))
self.tb_forword_2.setText(_translate("PyxisAd", "forword"))
self.tb_home.setText(_translate("PyxisAd", "home"))
self.tb_search.setText(_translate("PyxisAd", "search"))
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_())
As the title says, my plot does not update. The objetive is to initiate the plot when the button is clicked. The window pops up and the axis are formed, but no curve is plotted. i used pyqt5 in qt designer fr the GUI and pyqtgraph for the plot. if i wanted to add more plots in the same window whats the optimal way to do it. Thanks
Code:
from PyQt5 import QtCore, QtGui, QtWidgets
import os,serial,jeje_rc
os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"
import numpy as np
import pyqtgraph as pg
class Ui_MainWindow(object):
def ser(self):
self.raw = serial.Serial('COM4', 9600)
self.raw.close()
self.raw.open()
def update(self):
self.datos = self.raw.readline()
self.datos1 = self.datos.decode().split(',')
self.y1[self.m] = self.datos1[0]
if self.m == 99:
self.y1 = np.zeros(100, dtype=float)
self.m = 0
else:
self.m += 1
self.curva1.setData(self.y1)
app.processEvents()
def start(self):
self.ser()
self.win = pg.GraphicsWindow()
self.win.setWindowTitle('Datos de arduino')
self.p1 = self.win.addPlot()
self.p1.setYRange(0, 1024, padding=0)
self.curva1 = self.p1.plot()
self.datos = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
self.y1 = np.zeros(100, dtype=float)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowTitle("ECG de 12 Derivaciones UAO")
MainWindow.resize(800, 550)
self.m=0
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setMaximumSize(QtCore.QSize(805, 510))
self.centralwidget.setObjectName("centralwidget")
self.centralwidget.setWindowTitle("ECG de 12 Derivaciones UAO")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 270, 241, 19))
self.label.setObjectName("label")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(10, 230, 781, 20))
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(600, 40, 181, 171))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(40, 10, 591, 41))
font = QtGui.QFont()
font.setPointSize(16)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(170, 150, 221, 41))
font = QtGui.QFont()
font.setPointSize(11)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(110, 190, 471, 41))
font = QtGui.QFont()
font.setPointSize(11)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(50, 100, 521, 51))
font = QtGui.QFont()
font.setPointSize(9)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.lineEdad = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdad.setGeometry(QtCore.QRect(110, 310, 261, 21))
self.lineEdad.setObjectName("lineEdad")
self.lineNombre = QtWidgets.QLineEdit(self.centralwidget)
self.lineNombre.setGeometry(QtCore.QRect(110, 270, 261, 20))
self.lineNombre.setObjectName("lineNombre")
self.BotonInicio = QtWidgets.QPushButton(self.centralwidget)
self.BotonInicio.setGeometry(QtCore.QRect(490, 290, 181, 41))
self.BotonInicio.setObjectName("BotonInicio")
self.BotonInicio.clicked.connect(self.start)
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setGeometry(QtCore.QRect(20, 310, 68, 19))
self.label_7.setObjectName("label_7")
self.label_8 = QtWidgets.QLabel(self.centralwidget)
self.label_8.setGeometry(QtCore.QRect(20, 350, 61, 19))
self.label_8.setObjectName("label_8")
self.label_9 = QtWidgets.QLabel(self.centralwidget)
self.label_9.setGeometry(QtCore.QRect(20, 380, 111, 31))
self.label_9.setObjectName("label_9")
self.BoxGenero = QtWidgets.QComboBox(self.centralwidget)
self.BoxGenero.setGeometry(QtCore.QRect(110, 350, 92, 25))
self.BoxGenero.setObjectName("BoxGenero")
self.BoxGenero.addItem("")
self.BoxGenero.addItem("")
self.plainTextPatologias = QtWidgets.QPlainTextEdit(self.centralwidget)
self.plainTextPatologias.setGeometry(QtCore.QRect(110, 390, 261, 91))
self.plainTextPatologias.setObjectName("plainTextPatologias")
self.line_2 = QtWidgets.QFrame(self.centralwidget)
self.line_2.setGeometry(QtCore.QRect(390, 250, 20, 241))
self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.BotonExportar = QtWidgets.QPushButton(self.centralwidget)
self.BotonExportar.setGeometry(QtCore.QRect(490, 410, 181, 41))
self.BotonExportar.setObjectName("BotonExportar")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 805, 31))
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)
timer = QtCore.QTimer()
timer.timeout.connect(self.update)
timer.start(0)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "ECG de 12 Derivaciones"))
self.label.setText(_translate("MainWindow", "Nombre:"))
self.label_2.setText(_translate("MainWindow", "<html><head/><body><p><img src=\":/newPrefix/logo-universidad-autonoma-de-occidente.png\"/></p></body></html>"))
self.label_3.setText(_translate("MainWindow", "Electrocardiógrafo De 12 Derivaciones"))
self.label_4.setText(_translate("MainWindow", "Facultad de ingenieria"))
self.label_5.setText(_translate("MainWindow", " Universidad Autonoma De Occidente"))
self.label_6.setText(_translate("MainWindow", "Por: Mario Gomez, Viviana Calero, Sara Chillito, Stefania Calderon"))
self.BotonInicio.setText(_translate("MainWindow", "Inicio del programa"))
self.label_7.setText(_translate("MainWindow", "Edad:"))
self.label_8.setText(_translate("MainWindow", "Genero:"))
self.label_9.setText(_translate("MainWindow", "Patologias:"))
self.BoxGenero.setItemText(0, _translate("MainWindow", "Hombre"))
self.BoxGenero.setItemText(1, _translate("MainWindow", "Mujer"))
self.BotonExportar.setText(_translate("MainWindow", "Exportar datos"))
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_())
It is recommended not to modify the code provided by Qt Designer since if you want to modify the design you will have to rewrite your code, besides the Ui_MainWindow class is not a widget but a class that is used to fill some widget, so I recommend deleting the changes .
On the other hand is not suitable to run with a timer with a range of 0, since it does not allow updating the GUI, on the other hand the reading of the serial is blocking, so a possible solution is to use QThread, and use a signal to update the data in the GUI thread.
class Ui_MainWindow(object):
...
class ArduinoThread(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(str)
def __init__(self, *args, **kwargs):
QtCore.QThread.__init__(self, *args, **kwargs)
self.raw = serial.Serial('com4', 9600)
self.raw.close()
self.raw.open()
def run(self):
while True:
datos_array = self.raw.readline().decode().split(',')
if datos_array:
datos = datos_array[0]
self.dataChanged.emit(datos)
QtCore.QThread.msleep(10)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.BotonInicio.clicked.connect(self.start)
self.m = 0
def update_plot(self, dato):
if self.m > 99:
self.y1 = np.zeros(100, dtype=float)
self.m = 0
else:
self.y1[self.m] = dato
self.m += 1
self.curva1.setData(self.y1)
def start(self):
thread = ArduinoThread(self)
thread.dataChanged.connect(self.update_plot)
thread.start()
self.win = pg.GraphicsWindow()
self.win.setWindowTitle('Datos de arduino')
self.p1 = self.win.addPlot()
self.p1.setYRange(0, 1024, padding=0)
self.curva1 = self.p1.plot()
self.y1 = np.zeros(100, dtype=float)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
As you can see, I have made some changes to improve the application as verifications, use variables when necessary, etc.
Although a way compatible with Qt is to use QSerialPort that emits the readyRead signal when there is a new data:
from PyQt5 import QtCore, QtGui, QtWidgets, QtSerialPort
....
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.BotonInicio.clicked.connect(self.start)
def update_plot(self):
while self.ser.canReadLine():
line = bytearray(self.ser.readLine()).decode()
self.processLine(line)
def processLine(self, line):
datos_array = line.strip().split(',')
if datos_array:
dato = datos_array[0]
if self.m > 99:
self.y1 = np.zeros(100, dtype=float)
self.m = 0
else:
self.y1[self.m] = dato
self.m += 1
self.curva1.setData(self.y1)
def start(self):
self.ser = QtSerialPort.QSerialPort("com4", self)
self.ser.setBaudRate(9600)
self.ser.readyRead.connect(self.update_plot)
self.ser.open(QtSerialPort.QSerialPort.ReadOnly)
self.win = pg.GraphicsWindow()
self.win.setWindowTitle('Datos de arduino')
self.p1 = self.win.addPlot()
self.p1.setYRange(0, 1024, padding=0)
self.curva1 = self.p1.plot()
self.y1 = np.zeros(100, dtype=float)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())