Here is the code for a camera surveillance system. In the configuration_page.py file I'm getting the size of the window as 100x30 despite using self.showMaximized() and resizeEvent(). The widgets present in it are also showing the size as 640x480. I'm particularly interested in retrieving the size of a widget named self.mid_frame in CameraDisplay class present in config.py file.
Earlier I was facing the same issue in dashboard.py file but I found a workaround by explicitly passing width and height in that case. But this time I'm stuck because I need to get the size of the widget named self.mid_frame. I don't understand why even resizeEvent is showing the wrong size.
main.py
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt, QRect
from threading import Thread, RLock, Lock
from collections import deque
from datetime import datetime
import time
import sys
import cv2
import imutils
from dashboard import *
from configuration_page import *
from global_widgets import *
class CameraWidget(QtGui.QWidget):
"""Independent camera feed
Uses threading to grab IP camera frames in the background
#param width - Width of the video frame
#param height - Height of the video frame
#param stream_link - IP/RTSP/Webcam link
#param aspect_ratio - Whether to maintain frame aspect ratio or force into fraame
"""
def __init__(self, stream_link=0, stacked_widget=None, width=0, height=0, btn_text=None, idx=None, aspect_ratio=False, parent=None, deque_size=1):
super(CameraWidget, self).__init__(parent)
# Initialize deque used to store frames read from the stream
self.deque = deque(maxlen=deque_size)
self.maintain_aspect_ratio = aspect_ratio
self.camera_stream_link = stream_link
self.stacked_widget = stacked_widget
self.idx = idx
# Flag to check if camera is valid/working
self.online = False
self.capture = None
self.video_frame = QtGui.QLabel()
self.video_frame_1 = QtGui.QLabel()
self.load_network_stream()
# Start background frame grabbing
self.get_frame_thread = Thread(target=self.get_frame, args=())
self.get_frame_thread.daemon = True
self.get_frame_thread.start()
# Periodically set video frame to display
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.set_frame)
self.timer.start(.5)
print('Started camera: {}'.format(self.camera_stream_link))
def load_network_stream(self):
"""Verifies stream link and open new stream if valid"""
def load_network_stream_thread():
if self.verify_network_stream(self.camera_stream_link):
self.capture = cv2.VideoCapture(self.camera_stream_link)
self.online = True
self.load_stream_thread = Thread(target=load_network_stream_thread, args=())
self.load_stream_thread.daemon = True
self.load_stream_thread.start()
def verify_network_stream(self, link):
"""Attempts to receive a frame from given link"""
cap = cv2.VideoCapture(link)
if not cap.isOpened():
return False
cap.release()
return True
def get_frame(self):
"""Reads frame, resizes, and converts image to pixmap"""
while True:
try:
if self.capture.isOpened() and self.online:
# Read next frame from stream and insert into deque
status, frame = self.capture.read()
if status:
self.deque.append(frame)
else:
self.capture.release()
self.online = False
else:
# Attempt to reconnect
print('attempting to reconnect', self.camera_stream_link)
self.load_network_stream()
self.spin(2)
self.spin(.001)
except AttributeError:
pass
def spin(self, seconds):
"""Pause for set amount of seconds, replaces time.sleep so program doesnt stall"""
time_end = time.time() + seconds
while time.time() < time_end:
QtGui.QApplication.processEvents()
def set_frame(self):
"""Sets pixmap image to video frame"""
if not self.online:
self.spin(1)
return
if self.deque and self.online:
# Grab latest frame
frame = self.deque[-1]
frame_1 = self.deque[-1]
# Display frames on dashboard and configuration pages
# Frame for dashboard
# Keep frame aspect ratio
if self.maintain_aspect_ratio:
self.frame = imutils.resize(frame, width=self.screen_width)
# Force resize
else:
self.frame = cv2.resize(frame, (self.screen_width, self.screen_height))
self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
h, w, ch = self.frame.shape
bytesPerLine = ch * w
# Frame for configuration page-----------------------------------------------------------------------------------------
# print('2: ', self.screen_width_1, self.screen_height_1)
self.frame_1 = cv2.resize(frame_1, (self.screen_width_1, self.screen_height_1))
self.frame_1 = cv2.cvtColor(self.frame_1, cv2.COLOR_BGR2RGB)
h_1, w_1, ch_1 = self.frame_1.shape
bytesPerLine_1 = ch_1 * w_1
# Convert to pixmap and set to video frame
self.img = QtGui.QImage(self.frame, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)
self.pix = QtGui.QPixmap.fromImage(self.img)
self.video_frame.setPixmap(self.pix)
self.img_1 = QtGui.QImage(self.frame_1, w_1, h_1, bytesPerLine_1, QtGui.QImage.Format_RGB888)
self.pix_1 = QtGui.QPixmap.fromImage(self.img_1)
self.video_frame_1.setPixmap(self.pix_1)
def set_frame_params(self, width, height, btn_text=None, idx=0):
self.screen_width = width
self.screen_height = height
self.btn_text = btn_text
self.idx = idx
def set_frame_params_1(self, width, height):
self.screen_width_1 = width
self.screen_height_1 = height
def get_video_display_frame(self):
self.video_display_frame = QtGui.QFrame()
self.video_layout = QtGui.QVBoxLayout()
self.video_btn = QtGui.QPushButton(self.btn_text)
self.video_btn.setStyleSheet("background-color: rgb(128, 159, 255);")
self.video_btn.clicked.connect(self.on_clicked)
# self.video_frame = QtGui.QLabel()
self.video_frame.setScaledContents(True)
self.video_layout.addWidget(self.video_btn)
self.video_layout.addWidget(self.video_frame)
self.video_layout.setContentsMargins(0,0,0,0)
self.video_layout.setSpacing(0)
self.video_display_frame.setLayout(self.video_layout)
return self.video_display_frame
def get_video_frame(self):
self.video_frame_1.setScaledContents(True)
return self.video_frame_1
#QtCore.pyqtSlot()
def on_clicked(self):
GlobalObject().dispatchEvent("hello", args=(self.idx,))
self.stacked_widget.setCurrentIndex(1)
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.stacked_widget = QtGui.QStackedWidget()
layout = QtGui.QVBoxLayout()
layout.setContentsMargins(0,0,0,0)
layout.addWidget(self.stacked_widget)
widget = QtGui.QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
self.cam1 = CameraWidget(camera1, self.stacked_widget, idx=1)
widget_1 = DashBoard(self.cam1, self.stacked_widget)
widget_2 = ZoneConfig(self.cam1, self.stacked_widget)
self.stacked_widget.addWidget(widget_1)
self.stacked_widget.addWidget(widget_2)
self.showMaximized()
camera1 = '../streams/Fog.avi'
if __name__ == '__main__':
app = QtGui.QApplication([])
app.setStyle(QtGui.QStyleFactory.create("plastique"))
# app.setStyle(QtGui.QStyleFactory.create("Cleanlooks"))
window = Window()
window.show()
sys.exit(app.exec_())
dashboard.py
from PyQt4 import QtGui, QtCore
from global_widgets import *
class DashBoard(QtGui.QWidget):
def __init__(self, cam1, stacked_widget, parent=None):
super(DashBoard, self).__init__(parent)
self.showMaximized()
self.screen_width = self.width()
self.screen_height = self.height()
self.stacked_widget = stacked_widget
# Layouts and frames
layout = QtGui.QVBoxLayout()
top_frame = QtGui.QFrame()
top_frame.setStyleSheet("background-color: rgb(208, 208, 225)")
mid_frame = QtGui.QFrame()
mid_frame.setStyleSheet("background-color: rgb(153, 187, 255)")
layout.addWidget(top_frame, 1)
layout.addWidget(QHLine())
layout.addWidget(mid_frame, 20)
layout.setContentsMargins(0,0,0,0)
layout.setSpacing(0)
self.setLayout(layout)
# Top frame
label = QtGui.QLabel('Dashboard')
label.setFont(QtGui.QFont('Times New Roman', 20))
top_layout = QtGui.QHBoxLayout()
top_layout.addWidget(label, alignment=QtCore.Qt.AlignCenter)
top_layout.setContentsMargins(5,5,5,5)
top_frame.setLayout(top_layout)
# Middle frame
self.mid_layout = QtGui.QStackedLayout()
# Create camera widgets
print('Creating Camera Widgets...')
cam_widget = Cam1(cam1, self.screen_width, self.screen_height, self)
self.mid_layout.addWidget(cam_widget)
self.mid_layout.setCurrentWidget(cam_widget)
mid_frame.setLayout(self.mid_layout)
class Cam1(QtGui.QWidget):
def __init__(self, cam1, screen_width, screen_height, parent=None):
super(Cam1, self).__init__(parent)
cam1.set_frame_params(screen_width, screen_height, 'VIDS 01', 1)
# Add widgets to layout
print('Adding widgets to layout...')
layout = QtGui.QGridLayout()
layout.addWidget(cam1.get_video_display_frame(),0,0,1,1)
layout.setContentsMargins(5,5,5,5)
self.setLayout(layout)
configuration_page.py
from PyQt4 import QtGui, QtCore
from global_widgets import *
from ui_main import *
class ZoneConfig(QtGui.QWidget):
def __init__(self, cam1, stacked_widget, parent=None):
super(ZoneConfig, self).__init__(parent)
GlobalObject().addEventListener("hello", self.set_cam)
self.layout = QtGui.QVBoxLayout()
self.frame = QtGui.QFrame()
self.frame_layout = QtGui.QStackedLayout()
# self.setLayout(self.frame_layout)
self.screen_width = self.width()
self.screen_height = self.height()
cam_widget_1 = CameraDisplay(cam1, 1, self.frame_layout, stacked_widget, self)
self.frame_layout.addWidget(cam_widget_1)
self.frame.setLayout(self.frame_layout)
self.layout.addWidget(self.frame)
self.layout.setContentsMargins(0,0,0,0)
self.setLayout(self.layout)
#QtCore.pyqtSlot()
def set_cam(self, index):
if index == 1:
self.frame_layout.setCurrentIndex(0)
class CameraDisplay(QtGui.QWidget):
def __init__(self, cam, idx, frame_layout, stacked_widget, parent=None):
super(CameraDisplay, self).__init__(parent)
self.showMaximized()
self.screen_width = self.width()
self.screen_height = self.height()
self.frame_layout = frame_layout
self.stacked_widget = stacked_widget
print('size: ', self.screen_width, self.screen_height)
# Layouts and frames
layout = QtGui.QVBoxLayout()
top_frame = QtGui.QFrame()
top_frame.setStyleSheet("background-color: rgb(208, 208, 225)")
self.mid_frame = QtGui.QFrame() ## Size of this frame is needed
self.mid_frame.setStyleSheet("background-color: rgb(153, 187, 255)")
btm_frame = QtGui.QFrame()
btm_frame.setStyleSheet("background-color: rgb(208, 208, 225)")
# Top frame
label = QtGui.QLabel('Configuration')
label.setFont(QtGui.QFont('Times New Roman', 20))
top_layout = QtGui.QHBoxLayout()
top_layout.addWidget(label, alignment=QtCore.Qt.AlignCenter)
top_layout.setContentsMargins(5,5,5,5)
top_frame.setLayout(top_layout)
# Middle frame
mid_layout = QtGui.QHBoxLayout()
# Create camera widgets
print('Creating Camera Widgets...')
mid_layout = QtGui.QHBoxLayout()
self.video_frame = cam.get_video_frame()
mid_layout.addWidget(self.video_frame)
mid_layout.setContentsMargins(5,5,5,5)
self.mid_frame.setLayout(mid_layout)
# Bottom frame
btn = QtGui.QPushButton('Dashboard')
btn.clicked.connect(self.goMainWindow)
btm_layout = QtGui.QHBoxLayout()
btm_layout.addStretch()
btm_layout.addWidget(btn)
btm_layout.setContentsMargins(5,5,5,5)
btm_frame.setLayout(btm_layout)
layout.addWidget(top_frame, 1)
layout.addWidget(QHLine())
layout.addWidget(self.mid_frame, 50)
layout.addWidget(QHLine())
layout.addWidget(btm_frame, 1)
layout.setContentsMargins(0,0,0,0)
layout.setSpacing(0)
self.setLayout(layout)
# self.showMaximized()
cam.set_frame_params_1(self.mid_frame.width(), self.mid_frame.height()-10) ## here I want the size
def resizeEvent(self, event):
QtGui.QWidget.resizeEvent(self, event)
def goMainWindow(self):
self.stacked_widget.setCurrentIndex(0)
I think the problem is only in configuration_page.py file but I'm pasting entire code in case anyone wants to go throught the entire logic.
Add the following to your code.
def event(self, e):
if e.type() in (QEvent.Show, QEvent.Resize):
widget_w = self.mid_frame.frameGeometry().width()
widget_h = self.mid_frame.frameGeometry().height()
screen_w = self.width()
screen_h = self.height()
# For "debugging" purposes:
print("Widget - width: %s height: %s" % (widget_w, widget_h)
print("screen - width: %s height: %s" % (screen_w, screen_h)
return ((widget_w, widget_h), (screen_w, screen_h))
#return {"widget": {"width": widget_w, "height": widget_h}, "screen": {"width": screen_w, "height": screen_h}}
Related
Here is my code, It's Flashing When I runs it bur working both cameras, Also It is a Very difficult for me to put the camera display correctly one camera on left and other on right but tried a lot to do so. Actually I am a Beginner right now. It a Python Code in PYQT5 with OpenCV(Python) in it. I am going to use it on Raspberry.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import cv2
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.VBL = QVBoxLayout()
self.showMaximized()
self.FeedLabel = QLabel()
self.VBL.addWidget(self.FeedLabel)
self.setGeometry(0, 0, 1920, 1000)
self.VBL1 = QVBoxLayout()
# self.showMaximized()
# self.FeedLabel = QLabel()
# self.VBL1.addWidget(self.FeedLabel)
self.VBL1.setGeometry(QtCore.QRect(0, 0, 900, 1000))
self.setLayout(self.VBL)
self.VBL2 = QVBoxLayout()
# self.showMaximized()
# self.FeedLabel = QLabel()
# self.VBL2.addWidget(self.FeedLabel)
self.setGeometry(QtCore.QRect(QPoint(100, 200), QSize(11, 16)))
# self.setGeometry()
self.setLayout(self.VBL)
# self.CancelBTN = QPushButton(Cancel)
# self.CancelBTN.clicked.connect(self.CancelFeed)
# self.VBL.addWidget(self.CancelBTN)
# self.frame = QtWidgets.QFrame(self)
# self.frame.setGeometry(QtCore.QRect(1, 1, 200, 200))
# self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
# self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.Worker1 = Worker1()
self.Worker1.start()
self.Worker1.ImageUpdate1.connect(self.ImageUpdateSlot1)
self.setLayout(self.VBL1)
self.Worker2 = Worker2()
self.Worker2.start()
self.Worker2.ImageUpdate.connect(self.ImageUpdateSlot)
self.setLayout(self.VBL2)
def ImageUpdateSlot(self, Image):
self.FeedLabel.setPixmap(QPixmap.fromImage(Image))
def ImageUpdateSlot1(self, Image):
self.FeedLabel.setPixmap(QPixmap.fromImage(Image))
def CancelFeed(self):
self.Worker1.stop()
class Worker1(QThread):
ImageUpdate1 = pyqtSignal(QImage)
def run(self):
self.ThreadActive = True
Capture = cv2.VideoCapture(0)
while self.ThreadActive:
ret, frame = Capture.read()
if ret:
Image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
FlippedImage = cv2.flip(Image, 1)
ConvertToQtFormat = QImage(FlippedImage.data, FlippedImage.shape[1], FlippedImage.shape[0], QImage.Format_RGB888)
Pic = ConvertToQtFormat.scaled(960, 1080)
self.ImageUpdate1.emit(Pic)
def stop(self):
self.ThreadActive = False
self.quit()
class Worker2(QThread):
ImageUpdate = pyqtSignal(QImage)
def run(self):
self.ThreadActive = True
Capture = cv2.VideoCapture(1)
while self.ThreadActive:
ret, frame = Capture.read()
if ret:
Image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
FlippedImage = cv2.flip(Image, 1)
ConvertToQtFormat = QImage(FlippedImage.data, FlippedImage.shape[1], FlippedImage.shape[0], QImage.Format_RGB888)
Pic = ConvertToQtFormat.scaled(400, 800)
self.ImageUpdate.emit(Pic)
def stop(self):
self.ThreadActive = False
self.quit()
if __name__ == "__main__":
App = QApplication(sys.argv)
Root = MainWindow()
Root.show()
sys.exit(App.exec())
Try to link PyQt and Opencv video feed, can't understand how to apply while loop for continuously streaming video. It just take a still picture.Please can anyone help to solve the problem.
PtQt=5
Python=3.6.1
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 Video'
self.left = 100
self.top = 100
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.resize(1800, 1200)
#create a label
label = QLabel(self)
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
convertToQtFormat = QtGui.QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0],
QtGui.QImage.Format_RGB888)
convertToQtFormat = QtGui.QPixmap.fromImage(convertToQtFormat)
pixmap = QPixmap(convertToQtFormat)
resizeImage = pixmap.scaled(640, 480, QtCore.Qt.KeepAspectRatio)
QApplication.processEvents()
label.setPixmap(resizeImage)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
The problem is that the function that obtains the image is executed only once and not updating the label.
The correct way is to place it inside a loop, but it will result in blocking the main window. This blocking of main window can be solved by using the QThread class and send through a signal QImage to update the label. For example:
import cv2
import sys
from PyQt5.QtWidgets import QWidget, QLabel, QApplication
from PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlot
from PyQt5.QtGui import QImage, QPixmap
class Thread(QThread):
changePixmap = pyqtSignal(QImage)
def run(self):
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
# https://stackoverflow.com/a/55468544/6622587
rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = rgbImage.shape
bytesPerLine = ch * w
convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
self.changePixmap.emit(p)
class App(QWidget):
def __init__(self):
super().__init__()
[...]
self.initUI()
#pyqtSlot(QImage)
def setImage(self, image):
self.label.setPixmap(QPixmap.fromImage(image))
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.resize(1800, 1200)
# create a label
self.label = QLabel(self)
self.label.move(280, 120)
self.label.resize(640, 480)
th = Thread(self)
th.changePixmap.connect(self.setImage)
th.start()
self.show()
Updating this for PySide2 and qimage2ndarray
from PySide2.QtCore import *
from PySide2.QtGui import *
import cv2 # OpenCV
import qimage2ndarray # for a memory leak,see gist
import sys # for exiting
# Minimal implementation...
def displayFrame():
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = qimage2ndarray.array2qimage(frame)
label.setPixmap(QPixmap.fromImage(image))
app = QApplication([])
window = QWidget()
# OPENCV
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
# timer for getting frames
timer = QTimer()
timer.timeout.connect(displayFrame)
timer.start(60)
label = QLabel('No Camera Feed')
button = QPushButton("Quiter")
button.clicked.connect(sys.exit) # quiter button
layout = QVBoxLayout()
layout.addWidget(button)
layout.addWidget(label)
window.setLayout(layout)
window.show()
app.exec_()
# See also: https://gist.github.com/bsdnoobz/8464000
Thank you Taimur Islam for the question.
Thank you eyllanesc for wonderful answering and I have modified your code little bit. I used PtQt=4 Python=2.7 and I didn't use opencv
import sys
import numpy as np
import flycapture2 as fc2
from PyQt4.QtCore import (QThread, Qt, pyqtSignal)
from PyQt4.QtGui import (QPixmap, QImage, QApplication, QWidget, QLabel)
class Thread(QThread):
changePixmap = pyqtSignal(QImage)
def __init__(self, parent=None):
QThread.__init__(self, parent=parent)
self.cameraSettings()
def run(self):
while True:
im = fc2.Image()
self.c.retrieve_buffer(im)
a = np.array(im)
rawImage = QImage(a.data, a.shape[1], a.shape[0], QImage.Format_Indexed8)
self.changePixmap.emit(rawImage)
def cameraSettings(self):
print(fc2.get_library_version())
self.c = fc2.Context()
numberCam = self.c.get_num_of_cameras()
print(numberCam)
self.c.connect(*self.c.get_camera_from_index(0))
print(self.c.get_camera_info())
m, f = self.c.get_video_mode_and_frame_rate()
print(m, f)
print(self.c.get_property_info(fc2.FRAME_RATE))
p = self.c.get_property(fc2.FRAME_RATE)
print(p)
self.c.set_property(**p)
self.c.start_capture()
class App(QWidget):
def __init__(self):
super(App,self).__init__()
self.title = 'PyQt4 Video'
self.left = 100
self.top = 100
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.resize(800, 600)
# create a label
self.label = QLabel(self)
self.label.move(0, 0)
self.label.resize(640, 480)
th = Thread(self)
th.changePixmap.connect(lambda p: self.setPixMap(p))
th.start()
def setPixMap(self, p):
p = QPixmap.fromImage(p)
p = p.scaled(640, 480, Qt.KeepAspectRatio)
self.label.setPixmap(p)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import QApplication,QDialog,QPushButton,QVBoxLayout,QWidget
class Main(QDialog):
def __init__(self):
super(Main, self).__init__()
self.ui()
# Group Of Drage Event
def mousePressEvent(self,event):
self.offset = event.pos()
def mouseMoveEvent(self, e):
x = e.globalX()
y = e.globalY()
x_w = self.offset.x()
y_w = self.offset.y()
self.move(x - x_w, y - y_w)
def ui(self):
# TitleBar
self.setWindowFlags(Qt.FramelessWindowHint)
# Window Size
self.setGeometry(600,300,400,500)
# Window Background Color
self.BackGroundColor = QPalette()
self.BackGroundColor.setColor(QPalette.Background, QColor(255,255,255))
self.setPalette(self.BackGroundColor)
# NavBar Button
self.btn = QPushButton('Test',self)
self.btn1 = QPushButton("Test1",self)
# NavBar Layout
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.btn)
self.layout.addWidget(self.btn1)
self.layout.set
self.setLayout(self.layout)
# Close img
self.closeBtn = QPushButton(self)
self.closeBtn.setGeometry(368,0,32,32)
self.closeBtn.setFlat(True)
self.closeBtn.setStyleSheet('QPushButton{background-color: rgba(0,0,0,0.0)}')
self.closeBtn.setIcon(QIcon('img/close.png'))
self.closeBtn.setIconSize(QSize(10,10))
self.closeBtn.clicked.connect(QCoreApplication.instance().quit)
# Maximize icon
self.maxBtn = QPushButton(self)
self.maxBtn.setGeometry(self,336,0,32,32)
self.maxBtn.setFlat(True)
self.maxBtn.setStyleSheet('QPushButton{background-color: rgba(0,0,0,0.0)}')
self.maxBtn.setIcon(QIcon('img/max.png'))
self.maxBtn.setIconSize(QSize(14,14))
# Minimize Incon
self.minBtn = QPushButton(self)
self.minBtn.setGeometry(304,0,32,32)
self.minBtn.setFlat(True)
self.minBtn.setStyleSheet('QPushButton{background-color: rgba(0,0,0,0.0)}')
self.minBtn.setIcon(QIcon('img/min.png'))
self.minBtn.setIconSize(QSize(10,10))
def main():
app = QApplication()
win = Main()
win.show()
app.exec_()
if __name__ == "__main__":
main()
I want to fixed navbar on the left. So, I create instance of QVBoxLayout and add widget to my Layout. and I had searched google, stackoverflow. i Don't get any information about my problem
but I don't know how to set layout widget. please teach me. Thank you.
if you don't understand my text please tell me i will describe that
Version:
PySide 5.14.2.1
Python 3.7.7
The layouts are not visual elements, so they do not have any geometric element associated with them, such as the width size, the layout is a handle of size and positions.
In this case the solution is to establish a container with a fixed size and in that container place the buttons with the help of a layout:
class Main(QDialog):
def __init__(self):
super(Main, self).__init__()
self.ui()
# Group Of Drage Event
def mousePressEvent(self, event):
self.offset = event.pos()
def mouseMoveEvent(self, e):
x = e.globalX()
y = e.globalY()
x_w = self.offset.x()
y_w = self.offset.y()
self.move(x - x_w, y - y_w)
def ui(self):
# TitleBar
self.setWindowFlags(Qt.FramelessWindowHint)
# Window Size
self.setGeometry(600, 300, 400, 500)
# Window Background Color
self.BackGroundColor = QPalette()
self.BackGroundColor.setColor(QPalette.Background, QColor(255, 255, 255))
self.setPalette(self.BackGroundColor)
# NavBar Button
self.btn = QPushButton("Test")
self.btn1 = QPushButton("Test1")
left_container = QWidget(self)
left_container.setFixedWidth(100)
# NavBar layout
self.layout = QVBoxLayout(left_container)
self.layout.addWidget(self.btn)
self.layout.addWidget(self.btn1)
hlay = QHBoxLayout(self)
hlay.addWidget(left_container)
hlay.addStretch()
# Close img
self.closeBtn = QPushButton(self)
self.closeBtn.setGeometry(368, 0, 32, 32)
self.closeBtn.setFlat(True)
self.closeBtn.setStyleSheet("QPushButton{background-color: rgba(0,0,0,0.0)}")
self.closeBtn.setIcon(QIcon("img/close.png"))
self.closeBtn.setIconSize(QSize(10, 10))
self.closeBtn.clicked.connect(QCoreApplication.instance().quit)
# Maximize icon
self.maxBtn = QPushButton(self)
self.maxBtn.setGeometry(336, 0, 32, 32)
self.maxBtn.setFlat(True)
self.maxBtn.setStyleSheet("QPushButton{background-color: rgba(0,0,0,0.0)}")
self.maxBtn.setIcon(QIcon("img/max.png"))
self.maxBtn.setIconSize(QSize(14, 14))
# Minimize Incon
self.minBtn = QPushButton(self)
self.minBtn.setGeometry(304, 0, 32, 32)
self.minBtn.setFlat(True)
self.minBtn.setStyleSheet("QPushButton{background-color: rgba(0,0,0,0.0)}")
self.minBtn.setIcon(QIcon("img/min.png"))
self.minBtn.setIconSize(QSize(10, 10))
I am new to PyQT5 in Python2.7.
I like to have Verticle Layout with two components.
The first area is for Dispaly and the second area is for Control Widgets.
Now problem is (1)Control Widgets are not equally spaced and (2)First area needs more space than the second area.
How can I do that?
My code is as follow.
class Thread(QThread):
changePixmap = pyqtSignal(QImage)
def run(self):
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888)
p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
self.changePixmap.emit(p)
class PlayStreaming(QWidget):
def __init__(self):
super(PlayStreaming,self).__init__()
self.initUI()
#pyqtSlot(QImage)
def setImage(self, image):
self.label.setPixmap(QPixmap.fromImage(image))
def initUI(self):
self.setWindowTitle("Image")
self.setGeometry(100, 100, 600, 400)
self.resize(1800, 1200)
# create a label
self.label = QLabel(self)
self.label.move(280, 120)
self.label.resize(640, 480)
th = Thread(self)
th.changePixmap.connect(self.setImage)
th.start()
class UIWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
# Initialize tab screen
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tab3 = QWidget()
self.tabs.resize(800,600)
# Add tabs
self.tabs.addTab(self.tab1,"Face")
self.tabs.addTab(self.tab2,"Human")
self.tabs.addTab(self.tab3,"Vehicle")
# Create first tab
self.createGridLayout()
self.tab1.layout = QVBoxLayout(self)
self.display=PlayStreaming()
self.tab1.layout.addWidget(self.display)
self.tab1.layout.addWidget(self.horizontalGroupBox)
self.tab1.setLayout(self.tab1.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Control")
layout = QGridLayout()
layout.setColumnStretch(2, 3)
layout.addWidget(QPushButton('Test'),0,0)
layout.addWidget(QPushButton('Run'),0,1)
layout.addWidget(QPushButton('Set Faces'),0,2)
layout.addWidget(QPushButton('Recognize'),1,0)
layout.addWidget(QPushButton('Rescale'),1,1)
layout.addWidget(QPushButton('FacePose'),1,2)
self.horizontalGroupBox.setLayout(layout)
The current status is
How can I do that?
You must use the strech to set the weights, by default the stretch of each widget is 0 so you just need to set a stretch of 1 to self.display. On the other hand, it is not necessary to use setColumnStretch() since by default all buttons will have the same size:
from PyQt5 import QtCore, QtGui, QtWidgets
import cv2
class Thread(QtCore.QThread):
changePixmap = QtCore.pyqtSignal(QtGui.QImage)
def run(self):
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
convertToQtFormat = QtGui.QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QtGui.QImage.Format_RGB888)
p = convertToQtFormat.scaled(640, 480, QtCore.Qt.KeepAspectRatio)
self.changePixmap.emit(p)
class PlayStreaming(QtWidgets.QWidget):
def __init__(self):
super(PlayStreaming,self).__init__()
self.initUI()
#QtCore.pyqtSlot(QtGui.QImage)
def setImage(self, image):
self.label.setPixmap(QtGui.QPixmap.fromImage(image))
def initUI(self):
self.setWindowTitle("Image")
# create a label
self.label = QtWidgets.QLabel(self)
th = Thread(self)
th.changePixmap.connect(self.setImage)
th.start()
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.label, alignment=QtCore.Qt.AlignCenter)
class UIWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(UIWidget, self).__init__(parent)
# Initialize tab screen
self.tabs = QtWidgets.QTabWidget()
self.tab1 = QtWidgets.QWidget()
self.tab2 = QtWidgets.QWidget()
self.tab3 = QtWidgets.QWidget()
# Add tabs
self.tabs.addTab(self.tab1,"Face")
self.tabs.addTab(self.tab2,"Human")
self.tabs.addTab(self.tab3,"Vehicle")
# Create first tab
self.createGridLayout()
self.tab1.layout = QtWidgets.QVBoxLayout()
self.display = PlayStreaming()
self.tab1.layout.addWidget(self.display, stretch=1)
self.tab1.layout.addWidget(self.horizontalGroupBox)
self.tab1.setLayout(self.tab1.layout)
# Add tabs to widget
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
def createGridLayout(self):
self.horizontalGroupBox = QtWidgets.QGroupBox("Control")
layout = QtWidgets.QGridLayout()
layout.addWidget(QtWidgets.QPushButton('Test'),0,0)
layout.addWidget(QtWidgets.QPushButton('Run'),0,1)
layout.addWidget(QtWidgets.QPushButton('Set Faces'),0,2)
layout.addWidget(QtWidgets.QPushButton('Recognize'),1,0)
layout.addWidget(QtWidgets.QPushButton('Rescale'),1,1)
layout.addWidget(QtWidgets.QPushButton('FacePose'),1,2)
self.horizontalGroupBox.setLayout(layout)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = UIWidget()
w.show()
sys.exit(app.exec_())
I'm trying to get an image to fit my label entirely without using setScaledContents(True) since I'd like my ImageGrab to have the exact same dimensions as the QLabel space.
I use a PIL ImageGrab with a bbox. if I chance the parameters to a wider width and higher height it will crash the program without any errors. I have attached a picture where the Image in the Label is localed left center. I'd like it to the top left. So that it can expand down and to the right if I increased the size.
But I am curious as to why I am unable to increase the size of the bbox. (0, 0, 400, 220) works fine but (0, 0, 420, 220) will not upload the Image and closes down the GUI without any errors.
I'd like to have a ImageGrab with bbox (0, 0, 800, 700) and a QLabel with size(800, 700) so it can fit it perfectly.
class Main(QMainWindow):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setGeometry(200, 200, 1000, 700)
self.setWindowTitle('threads')
self.mainFrame = QFrame(self)
self.mainFrame.resize(1000, 650)
self.mainFrame.move(0, 50)
self.mainFrame.setStyleSheet("background-color: rbg(50, 50, 50)")
self.testButton = QPushButton("Click", self)
self.testButton.resize(500,30)
self.connect(self.testButton, SIGNAL("clicked()"), self.Capture)
self.label_ = QLabel(self.mainFrame)
self.label_.move(10, 10)
self.label_.resize(980, 630)
self.label_.setStyleSheet("background-color: rbg(150, 150, 150)")
#pyqtSlot(QImage)
def ChangeFrame(self, image):
pixmap = QPixmap.fromImage(image)
self.label_.setPixmap(pixmap)
def Capture(self):
self.thread_ = CaptureScreen()
self.connect(self.thread_, SIGNAL("ChangeFrame(QImage)"), self.ChangeFrame, Qt.QueuedConnection)
self.thread_.start()
class CaptureScreen(QThread):
pixmap = pyqtSignal(QImage)
def __init__(self, parent = None):
QThread.__init__(self)
def __del__(self):
print("?????")
self.exiting = True
self.wait()
def run(self):
while(True):
time.sleep(1/60)
img = ImageGrab.grab(bbox=(0, 0, 420, 220))
frame = ImageQt(img)
frame = QImage(frame)
self.emit( SIGNAL("ChangeFrame(QImage)"), frame)
The solution is to use layouts, and set the alignment in QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft.
I also recommend using the new connection syntax, on the other hand if you are going to inherit from QMainWindow in the constructor you must call it. And finally when you use QMainWindow you must set a central widget.
import time
from PyQt4 import QtCore, QtGui
from PIL import ImageGrab, ImageQt
class Main(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setGeometry(200, 200, 1000, 700)
self.setWindowTitle('threads')
main_widget = QtGui.QWidget()
self.setCentralWidget(main_widget)
lay = QtGui.QVBoxLayout(main_widget)
self.testButton = QtGui.QPushButton("Click")
self.testButton.setFixedHeight(30)
self.testButton.clicked.connect(self.capture)
mainFrame = QtGui.QFrame()
mainFrame.setStyleSheet("background-color: rbg(50, 50, 50)")
_lay = QtGui.QVBoxLayout(mainFrame)
_lay.setContentsMargins(0, 0, 0, 0)
self.label_ = QtGui.QLabel()
_lay.addWidget(self.label_, 0, QtCore.Qt.AlignTop|QtCore.Qt.AlignLeft)
lay.addWidget(self.testButton)
lay.addWidget(mainFrame)
#QtCore.pyqtSlot(QtGui.QImage)
def changeFrame(self, image):
pixmap = QtGui.QPixmap.fromImage(image)
self.label_.setPixmap(pixmap)
#QtCore.pyqtSlot()
def capture(self):
self.thread_ = CaptureScreen()
self.thread_.changedFrame.connect(self.changeFrame, QtCore.Qt.QueuedConnection)
self.thread_.start()
self.testButton.setDisabled(True)
class CaptureScreen(QtCore.QThread):
changedFrame = QtCore.pyqtSignal(QtGui.QImage)
def __del__(self):
print("?????")
self.exiting = True
self.quit()
self.wait()
def run(self):
while True:
time.sleep(1/60)
w, h = 420, 220
img = ImageGrab.grab(bbox=(0, 0, w, h))
frame = ImageQt.toqimage(img)
self.changedFrame.emit(QtGui.QImage(frame))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())