i'm trying to build an early stage video annotation software and i'm stuck here: if anyone know how OFOP works, i'm trying to do the same thing
For everyone else, my goal is to take a video recorded live from a camera (mainly a ROV camera) and stream on a window.
I'm stuck here with two codes (one for GUI and one for the software itself) and idk which one should i use to stream
This is the code i'm using for GUI
import sys
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QFileDialog, QVideoWidget
from PyQt6.Qtmultimedia import QMediaPlayer, QMediaContent
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Crea un widget centrale
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
# Crea un layout principale
main_layout = QVBoxLayout(central_widget)
# Crea un layout per la parte superiore
top_layout = QHBoxLayout()
main_layout.addLayout(top_layout)
# Crea un pulsante per aprire i file video
open_button = QPushButton("Apri video", self)
open_button.clicked.connect(self.open_video)
top_layout.addWidget(open_button)
# Crea un'etichetta per la descrizione
label = QLabel("Annotazione:", self)
top_layout.addWidget(label)
# Crea una casella di testo per le annotazioni
self.annotation_text = QLineEdit(self)
top_layout.addWidget(self.annotation_text)
# Crea un pulsante per salvare le annotazioni
save_button = QPushButton("Salva annotazione", self)
save_button.clicked.connect(self.save_annotation)
top_layout.addWidget(save_button)
# Crea un widget video
self.video_widget = QVideoWidget(self)
main_layout.addWidget(self.video_widget)
# Imposta le dimensioni della finestra principale
self.setGeometry(100, 100, 800, 600)
self.show()
def open_video(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "Apri file video", "", "Video Files (*.mp4 *.avi *.mkv);;All Files (*)", options=options)
if file_name:
self.media_player = QMediaPlayer(self)
self.media_player.setVideoOutput(self.video_widget)
self.media_player.setMedia(QMediaContent(file_name))
self.media_player.play()
def save_annotation(self):
annotation = self.annotation_text.text()
# Salva l'annotazione in un file o un database
# ...
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec())
This is for the software
import sys
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QFileDialog, QVideoWidget
from PyQt6.Qtmultimedia import QMediaPlayer, QMediaContent
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Crea un widget centrale
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
# Crea un layout principale
main_layout = QVBoxLayout(central_widget)
# Crea un layout per la parte superiore
top_layout = QHBoxLayout()
main_layout.addLayout(top_layout)
# Crea un pulsante per aprire i file video
open_button = QPushButton("Apri video", self)
open_button.clicked.connect(self.open_video)
top_layout.addWidget(open_button)
# Crea un'etichetta per la descrizione
label = QLabel("Annotazione:", self)
top_layout.addWidget(label)
# Crea una casella di testo per le annotazioni
self.annotation_text = QLineEdit(self)
top_layout.addWidget(self.annotation_text)
# Crea un pulsante per salvare le annotazioni
save_button = QPushButton("Salva annotazione", self)
save_button.clicked.connect(self.save_annotation)
top_layout.addWidget(save_button)
# Crea un widget video
self.video_widget = QVideoWidget(self)
main_layout.addWidget(self.video_widget)
# Imposta le dimensioni della finestra principale
self.setGeometry(100, 100, 800, 600)
self.show()
def open_video(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "Apri file video", "", "Video Files (*.mp4 *.avi *.mkv);;All Files (*)", options=options)
if file_name:
self.media_player = QMediaPlayer(self)
self.media_player.setVideoOutput(self.video_widget)
self.media_player.setMedia(QMediaContent(file_name))
self.media_player.play()
def save_annotation(self):
annotation = self.annotation_text.text()
# Salva l'annotazione in un file o un database
# ...
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec())
As far as u know is it better to take video from an IP address or directly through the camera itself? and how should i do it?
Related
This question already has an answer here:
PyQt5 label cut off
(1 answer)
Closed last year.
I have this Lable in my PyQt GUI: self.labelDirectory.setText("Insert directories name using a semicolumn (;) to separate them").
But in the actual application it's cutted and only show the first part of the text photo here
I tried using a new line (\n) but it doesn't do much with new line
full code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setGeometry(0, 0, 800, 800)
self.setWindowTitle("BocaWare")
self.initUi()
def initUi(self):
#data inizio
self.labelFirstDate = QtWidgets.QLabel(self)
self.labelFirstDate.setText("First Date")
self.labelFirstDate.move(20, 0)
self.firstDate = QtWidgets.QDateEdit(self)
self.firstDate.setGeometry(QtCore.QRect(10, 30, 100, 30))
#data fine
self.labelEndDate = QtWidgets.QLabel(self)
self.labelEndDate.setText("End Date")
self.labelEndDate.move(20, 60)
self.endDate = QtWidgets.QDateEdit(self)
self.endDate.setGeometry(QtCore.QRect(10, 85, 100, 30))
#casella testo per nome directory
self.labelDirectory = QtWidgets.QLabel(self)
#self.labelDirectory.setText("Inserire i nomi delle directory separati l'un l'altro con un punto e virgola (;)")
self.labelDirectory.setText("Insert directories \n name using a semicolumn (;) to separate them")
self.labelDirectory.move(20, 120)
self.directory = QtWidgets.QLineEdit(self)
self.directory.setGeometry(QtCore.QRect(10, 170, 400, 30))
#bottone invio
self.b1 = QtWidgets.QPushButton(self)
self.b1.setGeometry(QtCore.QRect(10, 200, 100, 30))
self.b1.setText("Submit")
self.b1.clicked.connect(self.submitClick)
def submitClick(self):
print(self.firstDate.date().toString("yyyy-MM-dd"))
print(self.endDate.date().toString("yyyy-MM-dd"))
print(self.directory.text())
directories = self.directory.text().split(";")
for directory in directories:
print(directory)
def window():
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
window()
Using some kind of layout is going to be helpful rather than manually sizing and positioning widgets. It looks like your label is just getting clipped based on its size, but rather than fixing that, maybe try a simple QFormLayout. You could also use a combinations of QVBoxLayout, QHBoxLayout, and QSpacer to achieve something similar.
form layout
from PyQt5 import QtWidgets
import sys
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 800, 800)
self.setWindowTitle("BocaWare")
self._init_ui()
def _init_ui(self):
self.central_widget = QtWidgets.QWidget(self)
self.setCentralWidget(self.central_widget)
self.layout = QtWidgets.QFormLayout(self.central_widget)
# data inizio
self.labelFirstDate = QtWidgets.QLabel(self)
self.labelFirstDate.setText("First Date")
self.firstDate = QtWidgets.QDateEdit(self)
# data fine
self.labelEndDate = QtWidgets.QLabel(self)
self.labelEndDate.setText("End Date")
self.endDate = QtWidgets.QDateEdit(self)
# casella testo per nome directory
self.labelDirectory = QtWidgets.QLabel(self)
# self.labelDirectory.setText("Inserire i nomi delle directory separati l'un l'altro con un punto e virgola (;)")
self.labelDirectory.setText("Insert directories name using a semicolumn (;) to separate them")
self.directory = QtWidgets.QLineEdit(self)
# bottone invio
self.b1 = QtWidgets.QPushButton(self)
self.b1.setText("Submit")
self.b1.clicked.connect(self.submit_click)
self.layout.addRow(self.labelFirstDate)
self.layout.addRow(self.firstDate)
self.layout.addRow(self.labelEndDate)
self.layout.addRow(self.endDate)
self.layout.addRow(self.labelDirectory)
self.layout.addRow(self.directory)
self.layout.addRow(self.b1)
def submit_click(self):
print(self.firstDate.date().toString("yyyy-MM-dd"))
print(self.endDate.date().toString("yyyy-MM-dd"))
print(self.directory.text())
directories = self.directory.text().split(";")
for directory in directories:
print(directory)
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
I am seeing gap into QVBoxLayout when I am placing layout it does not look good, any idea to fix issue
#!/usr/bin/env python
import os
import sys
from PySide2.QtCore import Qt, QSize, QRegExp, QFile, QTextStream
from PySide2.QtGui import QKeySequence, QTextCharFormat, QBrush,QColor, QTextDocument, QTextCursor
from PySide2.QtWidgets import (QApplication, QDesktopWidget, QMainWindow,
QPlainTextEdit, QGridLayout, QGroupBox,
QFormLayout, QHBoxLayout, QLabel, QLineEdit,
QMenu, QMenuBar, QPushButton, QMessageBox,
QTextEdit, QVBoxLayout, QWidget, QAction)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.width = 1100
self.height = 700
self.set_main_window()
self.create_violation_text()
def set_main_window(self):
"""
Setting main window position
"""
self.setWindowTitle("GUI %s" %(os.path.abspath(__file__)))
self.setFixedSize(QSize(self.width, self.height))
wid = QDesktopWidget()
screen_width = wid.screen().frameGeometry().width()
screen_height = wid.screen().frameGeometry().height()
self.setGeometry(screen_width/2-self.width/2,
screen_height/2-self.height/2,
self.width, self.height)
def create_violation_text(self):
"""
creating main violation window which contain all violations
"""
self.plain_textedit = QPlainTextEdit()
self.plain_textedit.setLineWrapMode(QPlainTextEdit.NoWrap)
self.plain_textedit.setStyleSheet(
"""QPlainTextEdit {font-size: 14pt;
font-family: Courier;}""")
class ReviewWindow(MainWindow):
def __init__(self, waiver_files, app):
"""creating Review mode"""
super().__init__()
self.waiver_files = waiver_files
self.app = app
def create_widget(self):
self.create_text_finder()
self.create_violation_window()
#order matter
main_layout = QVBoxLayout()
main_layout.addWidget(self.text_finder)
main_layout.addWidget(self.create_violation_box)
#creating widgeth object as main window does not
#add layout directly it add only widget
window = QWidget()
window.setLayout(main_layout)
self.setCentralWidget(window)
def create_text_finder(self):
"""
create text finder which wil search string into document
"""
self.text_finder = QGroupBox()
layout = QHBoxLayout()
label = QLabel()
label.setText("Keyword:")
self.line_edit = QLineEdit()
self.line_edit.setText("Enter your search here")
push_button = QPushButton("Find")
push_button.clicked.connect(self.find_string_match)
layout.addWidget(label)
layout.addWidget(self.line_edit)
layout.addWidget(push_button)
self.text_finder.setLayout(layout)
def create_violation_window(self):
"""
creating violation window which contain text editor,
violation type and checkbox
"""
self.create_violation_box = QGroupBox()
layout = QGridLayout()
layout.addWidget(self.plain_textedit, 1, 0, 12, 1)
layout.setColumnMinimumWidth(0, 10)
self.create_violation_box.setLayout(layout)
def find_string_match(self):
"""
Adding string match operation
"""
#format for desire match
format = QTextCharFormat()
format.setBackground(QBrush(QColor("red")))
pattern = QRegExp(self.line_edit.text())
text_document = self.plain_textedit.document()
#Reverting if any
text_document.undo()
if pattern.isEmpty():
QMessageBox.warning("Search filed is empty")
else:
find_cursor = QTextCursor(text_document)
cursor = QTextCursor(text_document)
cursor.beginEditBlock()
while (not find_cursor.isNull() and not find_cursor.atEnd()):
found = False
find_cursor = text_document.find(pattern, find_cursor,
QTextDocument.FindWholeWords)
if (not find_cursor.isNull()):
found = True
find_cursor.movePosition(QTextCursor.WordRight,
QTextCursor.KeepAnchor)
find_cursor.mergeCharFormat(format)
cursor.endEditBlock()
if __name__ == '__main__':
app = QApplication(sys.argv)
cwd = os.path.dirname(__file__)
waiver_file = \[os.path.join(cwd, fdata) for fdata in os.listdir(cwd)\]
window = ReviewWindow(waiver_file, app)
window.create_widget()
window.show()
app.exec_()
I wanted to create a secondary window to show the fullsized image, so that's what I've made but I can't see the image. I don't know if it's why I don't open correctly or what. I'm very new to Qt so provably it's a very simple mistake.
Thanks
Here's the code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
This is the main window, it has a open file dialog to select an image, once it have it puts the image in a label. When you click the button "Ampliar" you open a second window with should show the image with the original size.
# Classe per la finestra principal de l'App
class Ui_MainWindow(object):
# Inicialitzacio de variables
def __init__(self):
self.fileName = None
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1080, 720)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
# Label on coloquem la nostra imatge
self.lMarcIm = QtWidgets.QLabel(self.centralwidget)
self.lMarcIm.setGeometry(QtCore.QRect(10, 10, 500, 500))
self.lMarcIm.setAutoFillBackground(False)
self.lMarcIm.setScaledContents(True)
self.lMarcIm.setObjectName("lMarcIm")
# Boto per carregar una imatge al programa
self.bObrirIm = QtWidgets.QPushButton(self.centralwidget)
self.bObrirIm.setGeometry(QtCore.QRect(10, 530, 111, 31))
self.bObrirIm.setObjectName("bObrirIm")
self.bObrirIm.clicked.connect(self.obrirDialegImatge)
# Boto per ampliar la imatge carregada
self.bAmpliarIm = QtWidgets.QPushButton(self.centralwidget)
self.bAmpliarIm.setGeometry(QtCore.QRect(130, 530, 121, 31))
self.bAmpliarIm.setObjectName("bAmpliarIm")
self.bAmpliarIm.clicked.connect(self.ampliarImatge)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
################################################################
# Bloc de Funcions #
################################################################
def obrirDialegImatge(self):
# Obrim la finestra de dialeg i obtenim el nom
options = QtWidgets.QFileDialog.Options()
options |= QtWidgets.QFileDialog.DontUseNativeDialog
self.fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
None,
"QFileDialog.getOpenFileName()",
"",
"All Files (*);;Python Files (*.py)",
options=options)
# Posem l'imatge on toca del Layout
self.lMarcIm.setPixmap(QtGui.QPixmap(self.fileName))
def ampliarImatge(self):
#Comprovem que hi ha una imatge seleccionada
if self.fileName != None:
print("Imatge en gran")
self.openSecondWindow()
else:
self.popup_errorAmpliar()
def openSecondWindow(self):
self.secondWindow = QtWidgets.QMainWindow()
self.ui = Ui_SecondaryWindow()
self.ui.setupUi(self.secondWindow, self.fileName)
self.secondWindow.show()
def popup_errorAmpliar(self):
msg = QMessageBox()
msg.setWindowTitle("Alerta!")
msg.setText("No hi ha cap imatge carregada")
msg.setIcon(QMessageBox.Warning)
x = msg.exec_()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Image Processing APP"))
self.lMarcIm.setText(_translate("MainWindow", "TextLabel"))
self.bObrirIm.setText(_translate("MainWindow", "Obrir Imatge"))
self.bAmpliarIm.setText(_translate("MainWindow", "Ampliar"))
This is the secondary class, where I want to put the image I open in the other window, it recive it's path so I think it has to be easy
# Classe per la finestra secundaria de l'App
class Ui_SecondaryWindow(object):
def setupUi(self, SecondaryWindow, im):
SecondaryWindow.setObjectName("SecondaryWindow")
SecondaryWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondaryWindow)
self.centralwidget.setObjectName("centralwidget")
self.lmidaOriginal = QtWidgets.QLabel(self.centralwidget)
self.lmidaOriginal.setGeometry(QtCore.QRect(150, 60, 251, 101))
self.lmidaOriginal.setObjectName("lmidaOriginal")
self.openImage(im)
SecondaryWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(SecondaryWindow)
QtCore.QMetaObject.connectSlotsByName(SecondaryWindow)
def openImage(self, imRoute):
print(imRoute)
pixmap = QtGui.QPixmap("imRoute")
self.lmidaOriginal.setPixmap(pixmap)
#self.lmidaOriginal.resize(pixmap.width(), pixmap.height())
def retranslateUi(self, SecondaryWindow):
_translate = QtCore.QCoreApplication.translate
SecondaryWindow.setWindowTitle(_translate("SecondaryWindow", "Apmliated Image"))
self.lmidaOriginal.setText(_translate("SecondaryWindow", "TextLabel"))
this is the main
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_())
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
# Classe per la finestra secundaria de l'App
class Ui_SecondaryWindow(object):
def setupUi(self, SecondaryWindow): #, im):
SecondaryWindow.setObjectName("SecondaryWindow")
# SecondaryWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondaryWindow)
self.centralwidget.setObjectName("centralwidget")
self.lmidaOriginal = QtWidgets.QLabel(self.centralwidget)
# self.lmidaOriginal.setGeometry(QtCore.QRect(150, 60, 251, 101))
self.lmidaOriginal.setObjectName("lmidaOriginal")
# self.openImage(im)
SecondaryWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(SecondaryWindow)
QtCore.QMetaObject.connectSlotsByName(SecondaryWindow)
"""
def openImage(self, imRoute):
print("imRoute---", imRoute)
pixmap = QtGui.QPixmap("imRoute")
pixmap = QtGui.QPixmap(imRoute) #("im.png") #(imRoute)
self.lmidaOriginal.setPixmap(pixmap)
"""
def retranslateUi(self, SecondaryWindow):
_translate = QtCore.QCoreApplication.translate
SecondaryWindow.setWindowTitle(_translate("SecondaryWindow", "Apmliated Image"))
self.lmidaOriginal.setText(_translate("SecondaryWindow", "TextLabel"))
# Classe per la finestra principal de l'App
class Ui_MainWindow(object):
# Inicialitzacio de variables
def __init__(self):
self.fileName = None
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1080, 720)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
# Label on coloquem la nostra imatge
self.lMarcIm = QtWidgets.QLabel(self.centralwidget)
self.lMarcIm.setGeometry(QtCore.QRect(10, 10, 500, 500))
self.lMarcIm.setAutoFillBackground(False)
self.lMarcIm.setScaledContents(True)
self.lMarcIm.setObjectName("lMarcIm")
# Boto per carregar una imatge al programa
self.bObrirIm = QtWidgets.QPushButton(self.centralwidget)
self.bObrirIm.setGeometry(QtCore.QRect(10, 530, 111, 31))
self.bObrirIm.setObjectName("bObrirIm")
self.bObrirIm.clicked.connect(self.obrirDialegImatge)
# Boto per ampliar la imatge carregada
self.bAmpliarIm = QtWidgets.QPushButton(self.centralwidget)
self.bAmpliarIm.setGeometry(QtCore.QRect(130, 530, 121, 31))
self.bAmpliarIm.setObjectName("bAmpliarIm")
self.bAmpliarIm.clicked.connect(self.ampliarImatge)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
################################################################
# Bloc de Funcions #
################################################################
def obrirDialegImatge(self):
# Obrim la finestra de dialeg i obtenim el nom
options = QtWidgets.QFileDialog.Options()
options |= QtWidgets.QFileDialog.DontUseNativeDialog
self.fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
None,
"Select Image",
"",
"Image Files (*.png *.jpg *.jpeg *.bmp)", # +++
options=options)
# Posem l'imatge on toca del Layout
self.lMarcIm.setPixmap(QtGui.QPixmap(self.fileName))
def ampliarImatge(self):
#Comprovem que hi ha una imatge seleccionada
if self.fileName != None:
print("Imatge en gran")
self.openSecondWindow()
else:
self.popup_errorAmpliar()
def openSecondWindow(self):
self.secondWindow = QtWidgets.QMainWindow()
self.ui = Ui_SecondaryWindow()
# self.ui.setupUi(self.secondWindow, self.fileName)
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
self.ui.setupUi(self.secondWindow)
self.ui.lmidaOriginal.setPixmap(QtGui.QPixmap(self.fileName))
self.ui.lmidaOriginal.adjustSize()
self.secondWindow.resize(self.ui.lmidaOriginal.width(), self.ui.lmidaOriginal.height())
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self.secondWindow.show()
def popup_errorAmpliar(self):
msg = QMessageBox()
msg.setWindowTitle("Alerta!")
msg.setText("No hi ha cap imatge carregada")
msg.setIcon(QMessageBox.Warning)
x = msg.exec_()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Image Processing APP"))
self.lMarcIm.setText(_translate("MainWindow", "TextLabel"))
self.bObrirIm.setText(_translate("MainWindow", "Obrir Imatge"))
self.bAmpliarIm.setText(_translate("MainWindow", "Ampliar"))
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_())
from PyQt5.QtWidgets import QMainWindow, QApplication,QLineEdit, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout
from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread,
QThreadPool, pyqtSignal)
import sys
import os
from shutil import copy2
import _thread
import time
class AThread(QThread):
def run(self):
count = 0
while count < 5:
time.sleep(1)
print("A Increasing")
count += 1
class Example(QWidget):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.setWindowTitle('Learn')
self.setGeometry(300, 300, 300, 150)
self.layout = QVBoxLayout(self)
# Initialize tab screen
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)
# Add tabs
self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")
# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.pushButton1 = QPushButton("PyQt5 button")
self.pushButton1.clicked.connect(self.ON_PRESS)
self.textbox = QLineEdit(self)
self.tab1.layout.addWidget(self.textbox )
self.tab1.layout.addWidget(self.pushButton1)
self.tab1.setLayout(self.tab1.layout)
#Create Textbox inputs
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def using_q_thread(self):
app = Example()
thread = AThread()
thread.start()
sys.exit(app.exec_())
def ON_PRESS(self):
###Here is the Issue
try:
self.using_q_thread()
except:
print ("Error: unable to start thread")
###Drag and Drop files to directory
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
Hoping I am asking this correctly, but whenever using QThread there appears to be a bit of a hiccup. the first attempt to access the threaded function causes the try statement to fail, but then it immediately works. Im just curious if this is part of the functionality or if there is any issue with my code.
Avoid using try-except as you see hidden the error, in my personal case I avoid using it as far as I can for this type of problems.
I do not see it necessary to create another Example within using_q_thread, another problem is that thread is a local variable that will be eliminated, so thread must be a member of the class for its scope to increase.
import sys
import time
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTabWidget, QPushButton, QLineEdit
class AThread(QThread):
def run(self):
count = 0
while count < 5:
time.sleep(1)
print("A Increasing")
count += 1
class Example(QWidget):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.setWindowTitle('Learn')
self.setGeometry(300, 300, 300, 150)
self.layout = QVBoxLayout(self)
# Initialize tab screen
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)
# Add tabs
self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")
# Create first tab
self.tab1.layout = QVBoxLayout()
self.pushButton1 = QPushButton("PyQt5 button")
self.pushButton1.clicked.connect(self.ON_PRESS)
self.textbox = QLineEdit(self)
self.tab1.layout.addWidget(self.textbox )
self.tab1.layout.addWidget(self.pushButton1)
self.tab1.setLayout(self.tab1.layout)
#Create Textbox inputs
# Add tabs to widget
self.layout.addWidget(self.tabs)
def using_q_thread(self):
self.thread = AThread()
self.thread.start()
def ON_PRESS(self):
self.using_q_thread()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
I've written the following code to open image file using a menubar in PyQt5. It is able to select the file but not able to display it in the window. I've successfully opened text file but not able to do the same for images. Can you please rectify my error?
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QLabel, QFileDialog, QAction
from PyQt5.QtGui import QIcon, QPixmap
class MainWindow(QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
editMenu = menubar.addMenu('Edit')
self.resize(500, 500)
dlg = QFileDialog(self)
openAction = QAction('Open Image', self)
openAction.triggered.connect(self.openImage)
fileMenu.addAction(openAction)
closeAction = QAction('Exit', self)
closeAction.triggered.connect(self.close)
fileMenu.addAction(closeAction)
def openImage(self):
# This function is called when the user clicks File->Open Image.
label = QLabel(self)
filename = QFileDialog.getOpenFileName()
imagePath = filename[0]
print(imagePath)
pixmap = QPixmap(imagePath)
label.setPixmap(pixmap)
self.resize(pixmap.width(),pixmap.height())
self.show()
def main():
app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
if __name__ == '__main__':
sys.exit(main())
When you call show() the widget makes children visible, in your case QLabel is not a child when that method is used, so a trivial but partial solution is to make it visible:
def openImage(self):
label = QLabel(self)
label.show()
# or
# self.show()
But in the case of QMainWindow is not suitable, QMainWindow is a very special widgets because it has a definite structure as shown in the following image:
As you can see, QLabel is the centralWidget and create it only once, and then you only have to replace the QPixmap if you select a new image:
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QFileDialog, QAction
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
editMenu = menubar.addMenu('Edit')
self.resize(500, 500)
openAction = QAction('Open Image', self)
openAction.triggered.connect(self.openImage)
fileMenu.addAction(openAction)
closeAction = QAction('Exit', self)
closeAction.triggered.connect(self.close)
fileMenu.addAction(closeAction)
self.label = QLabel()
self.setCentralWidget(self.label)
def openImage(self):
imagePath, _ = QFileDialog.getOpenFileName()
pixmap = QPixmap(imagePath)
self.label.setPixmap(pixmap)
self.resize(pixmap.size())
self.adjustSize()
def main():
app = QApplication(sys.argv)
win = MainWindow()
win.show()
return app.exec_()
if __name__ == '__main__':
sys.exit(main())