I'm trying to make a sort of image viewer in which I put a background image ("Affichage du mur" button) and then I load images with the "Importer l'oeuvre" button (you can load as many images you want). It works fine but I would like that we could delete the images ... in fact I would like the image that we delete is the image selected by the user. I can't get the selected image to be deleted with the "Suppression de l'oeuvre" button ... it seems that there is a selectedItems() method but I don't know how to use it in my code. Can you help me please ? Here is a very simplified code of what I am doing :
import os, sys
try : import Image
except ImportError : from PIL import Image
# Imports PyQt5 -----------------------------------------------------------------------
from PyQt5.QtWidgets import QPushButton, QGridLayout, QGraphicsScene, QGraphicsView, \
QGraphicsPixmapItem, QGraphicsItem, QApplication, \
QMainWindow, QFileDialog, QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QColor, QTransform
# --------------------------------------------------------------------------------------
class TEST(QMainWindow):
def __init__(self):
super(TEST, self).__init__()
self.setWindowTitle('TEST')
self.setGeometry(10, 20, 1280, 760)
self.setMinimumSize(1280, 760)
# ----------------------------------------
self.graphe_vue = MonGraphiqueVueMur()
# ----------------------------------------
bout_visio_mur = QPushButton("Affichage du mur")
bout_visio_mur.setMaximumWidth(230)
bout_visio_mur.setMinimumWidth(230)
bout_visio_oeuvre = QPushButton("Importer l'oeuvre")
bout_visio_oeuvre.setMaximumWidth(230)
bout_visio_oeuvre.setMinimumWidth(230)
bout_supprimer_oeuvre = QPushButton("Suppression de l'oeuvre")
bout_supprimer_oeuvre.setMaximumWidth(230)
bout_supprimer_oeuvre.setMinimumWidth(230)
# ------------------------------------------------------------
bout_visio_mur.clicked.connect(self.graphe_vue.afficher_mur)
bout_visio_oeuvre.clicked.connect(self.graphe_vue.afficher_image_oeuvre)
bout_supprimer_oeuvre.clicked.connect(self.graphe_vue.supprimer_image_oeuvre)
# ------------------------------------------------------------
grid = QGridLayout()
grid.addWidget(self.graphe_vue, 0, 0)
grid.addWidget(bout_visio_mur, 1, 0)
grid.addWidget(bout_visio_oeuvre, 2, 0)
grid.addWidget(bout_supprimer_oeuvre, 3, 0)
widget = QWidget()
widget.setLayout(grid)
self.setCentralWidget(widget)
class MaScene(QGraphicsScene) :
def __init__(self, parent=None) :
super(MaScene, self).__init__(parent)
class MonGraphiquePixmapItemMur(QGraphicsPixmapItem) :
def __init__(self, parent=None):
super(MonGraphiquePixmapItemMur, self).__init__(parent)
class MonGraphiquePixmapItemOeuvre(QGraphicsPixmapItem) :
def __init__(self, parent=None):
super(MonGraphiquePixmapItemOeuvre, self).__init__(parent)
self.setFlag(QGraphicsItem.ItemIsMovable, True)
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.setFlag(QGraphicsItem.ItemIsFocusable, True)
self.setAcceptHoverEvents(True)
def hoverEnterEvent(self, event):
print('setAcceptHoverEvents --> Position', event.pos(), type(event.pos()), type(event.pos().x()), type(event.pos().x()))
print("Position X", event.pos().x(), "Position Y", event.pos().y())
class MonGraphiqueVueMur(QGraphicsView) :
backgroundcolor = QColor(100, 100, 100)
def __init__(self, parent=None) :
super(MonGraphiqueVueMur, self).__init__(parent)
self.setBackgroundBrush(self.backgroundcolor)
self.scene = MaScene()
self.setScene(self.scene)
def wheelEvent(self, event):
zoomInFactor = 1.1
zoomOutFactor = 1 / zoomInFactor
self.setTransformationAnchor(QGraphicsView.NoAnchor)
self.setResizeAnchor(QGraphicsView.NoAnchor)
oldPos = self.mapToScene(event.pos())
if event.angleDelta().y() > 0:
zoomFactor = zoomInFactor
else:
zoomFactor = zoomOutFactor
self.scale(zoomFactor, zoomFactor)
newPos = self.mapToScene(event.pos())
delta = newPos - oldPos
self.translate(delta.x(), delta.y())
def afficher_mur(self) :
ouv = QFileDialog.getOpenFileName(self, 'Ouvrir une image', os.path.expanduser('~'), 'Images (*.jpg *.jpeg *.JPG *.JPEG *.png *.gif)')[0]
chemin_fichier = str(ouv)
img_mur = Image.open(chemin_fichier)
self.scene.clear()
self.items().clear()
largeur, hauteur = img_mur.size
pixmap = QPixmap(chemin_fichier)
item = MonGraphiquePixmapItemMur(pixmap)
item.setTransformationMode(Qt.SmoothTransformation)
self.scene.addItem(item)
self.setScene(self.scene)
self.fitInView(item, Qt.KeepAspectRatio)
x, y = 0, 0
self.setSceneRect(-x, -y, largeur, hauteur)
self.centerOn(10, 10)
self.show()
def afficher_image_oeuvre(self) :
ouv = QFileDialog.getOpenFileName(self, 'Ouvrir une image', os.path.expanduser('~'), 'Images (*.jpg *.jpeg *.JPG *.JPEG *.png *.gif)')[0]
chemin_fichier = str(ouv)
pixmap = QPixmap(chemin_fichier)
pixmap = pixmap.scaled(700, 700, Qt.KeepAspectRatio, Qt.SmoothTransformation)
item = MonGraphiquePixmapItemOeuvre(pixmap)
item.setTransformationMode(Qt.SmoothTransformation)
item.setFlag(QGraphicsItem.ItemIsFocusable)
self.scene.addItem(item)
self.setScene(self.scene)
###################################################################################
iteme = self.scene.selectedItems()
print("iteme", iteme) # Return []
###################################################################################
self.show()
def supprimer_image_oeuvre(self) :
import sip
tous_items = list(self.scene.items())
print("len(tous_items)", len(tous_items))
print("tous_items", tous_items)
for i in tous_items :
if str(type(i)) != "<class '__main__.MonGraphiquePixmapItemMur'>" :
self.scene.removeItem(tous_items[0])
sip.delete(tous_items[0])
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = TEST()
ex.show()
sys.exit(app.exec_())
Thanks in advance.
I'd have other questions to ask but we'll see that later.
You just have to cycle through selectedItems(), there's absolutely no need to use the sip module, nor check the class using the string (which is not a good way to do so).
def supprimer_image_oeuvre(self) :
for item in self.scene.selectedItems():
self.scene.removeItem(item)
Related
I'm trying to subclass QFontDialog and would like to retrieve the characteristics of the selected font. If I use getFont() a QFontDialog window appears first, ... I'm certainly doing something wrong.
Here's my example code :
from PyQt5.QtWidgets import (QFontDialog, QPushButton,
QMainWindow, QApplication,
QTabWidget, QWidget, QVBoxLayout)
import sys
class FontSelection(QFontDialog) :
def __init__(self, parent=None):
super(FontSelection, self).__init__(parent)
self.setOption(self.DontUseNativeDialog, True)
self.bouton = self.findChildren(QPushButton)
self.intitule_bouton = self.bouton[0].text().lower()
self.ouvertureBouton = [x for x in self.bouton if self.intitule_bouton in str(x.text()).lower()][0]
self.ouvertureBouton.clicked.disconnect()
self.ouvertureBouton.clicked.connect(self.font_recup)
def font_recup(self) :
self.font_capture()
def font_capture(self) :
if self.intitule_bouton in ['ok', '&ok'] :
font, self.intitule_bouton = self.getFont()
print(font)
class MainQFontDialogTry(QMainWindow):
def __init__(self):
super(MainQFontDialogTry, self).__init__()
self.setWindowTitle('QFontDialog subclassed try')
self.setGeometry(0, 0, 1000, 760)
self.setMinimumSize(1000, 760)
self.tab_widget = QTabWidget()
self.win_widget_1 = FontSelection(self)
widget = QWidget()
layout = QVBoxLayout(widget)
self.tab_widget.addTab(self.win_widget_1, "QFontDialog Tab")
layout.addWidget(self.tab_widget)
self.setCentralWidget(widget)
self.qfont = FontSelection()
self.qfont.font_recup()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainQFontDialogTry()
ex.show()
sys.exit(app.exec_())
I'm trying to make pyqt5 Gui that shows a webcam live feed, records the feed at the same time, and saves it locally when closed. I managed to acheieve this using Timer(QTimer) in pyqt gui but When I try to implement it using Qthread (Which I really require) only the live feed is working.
Whenever I add Code required for recording video and run the program it says Python has Stopped Working and closes. Here is my Code:
import cv2
import sys
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QVBoxLayout
from PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlot
from PyQt5.QtGui import QImage, QPixmap
class Thread(QThread):
changePixmap = pyqtSignal(QImage)
def run(self):
self.cap = cv2.VideoCapture(0)
self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
self.writer = cv2.VideoWriter('output.avi', self.codec, 30.0, (self.width, self.height))
while self.cap.isOpened():
ret, self.frame = self.cap.read()
if ret:
self.frame = cv2.flip(self.frame, 1)
rgbimage = cv2.cvtColor(self.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 MyApp(QWidget):
def __init__(self):
super(MyApp, self).__init__()
self.title = 'Camera'
self.initUI()
def initUI(self):
self.label = QLabel(self)
lay = QVBoxLayout()
lay.addWidget(self.label)
self.setLayout(lay)
self.th = Thread()
self.th.changePixmap.connect(self.setImage)
self.th.start()
self.show()
#pyqtSlot(QImage)
def setImage(self, image):
self.label.setPixmap(QPixmap.fromImage(image))
self.th.writer.write(image)
def main():
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I tried placing the .write() inside the run() of Thread class as well which is showing the same error. Can you guys point out What I'm doing wrong and how to make it work. I'm new to python and pyqt.
Thanks in Advance.
You need to separate threads. First thread is for signal, second is for the record and the main thread is for GUI. Try the following code. There is a button to start/stop the record.
import sys
import cv2
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer, QThread, pyqtSignal, pyqtSlot
from PyQt5 import QtWidgets, QtCore, QtGui
#https://ru.stackoverflow.com/a/1150993/396441
class Thread1(QThread):
changePixmap = pyqtSignal(QImage)
def __init__(self, *args, **kwargs):
super().__init__()
def run(self):
self.cap1 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
self.cap1.set(3,480)
self.cap1.set(4,640)
self.cap1.set(5,30)
while True:
ret1, image1 = self.cap1.read()
if ret1:
im1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
height1, width1, channel1 = im1.shape
step1 = channel1 * width1
qImg1 = QImage(im1.data, width1, height1, step1, QImage.Format_RGB888)
self.changePixmap.emit(qImg1)
class Thread2(QThread):
def __init__(self, *args, **kwargs):
super().__init__()
self.active = True
def run(self):
if self.active:
self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
self.out1 = cv2.VideoWriter('output.avi', self.fourcc, 30, (640,480))
self.cap1 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
self.cap1.set(3, 480)
self.cap1.set(4, 640)
self.cap1.set(5, 30)
while self.active:
ret1, image1 = self.cap1.read()
if ret1:
self.out1.write(image1)
self.msleep(10)
def stop(self):
self.out1.release()
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.resize(660, 520)
self.control_bt = QPushButton('START')
self.control_bt.clicked.connect(self.controlTimer)
self.image_label = QLabel()
self.saveTimer = QTimer()
self.th1 = Thread1(self)
self.th1.changePixmap.connect(self.setImage)
self.th1.start()
vlayout = QVBoxLayout(self)
vlayout.addWidget(self.image_label)
vlayout.addWidget(self.control_bt)
#QtCore.pyqtSlot(QImage)
def setImage(self, qImg1):
self.image_label.setPixmap(QPixmap.fromImage(qImg1))
def controlTimer(self):
if not self.saveTimer.isActive():
# write video
self.saveTimer.start()
self.th2 = Thread2(self)
self.th2.active = True
self.th2.start()
# update control_bt text
self.control_bt.setText("STOP")
else:
# stop writing
self.saveTimer.stop()
self.th2.active = False
self.th2.stop()
self.th2.terminate()
# update control_bt text
self.control_bt.setText("START")
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
you placed the .write() inside the run() of Thread class is right way.
like:
...
while self.cap.isOpened():
ret, self.frame = self.cap.read()
if ret:
self.frame = cv2.flip(self.frame, 1)
rgbimage = cv2.cvtColor(self.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)
# put your writer() here, make sure your param is frame
# not converted to QtImage format
self.writer.write(rgbimage)
self.changePixmap.emit(p)
...
it's a little complicated but I will try
I have a panel or a button 'file' for the choice of a file and the opening of this file is a .nc file (netCDF4) so I would like to visualize it but the problem I would like to see it in one other panel which will be like a quicklook, and each time you have to choose a file of type .nc or directly to be visualized on the other panel
and here is part of my code for 2 panels:
class LeftPanelTop(wx.Panel): # panel choose file
def __init__(self, parent):
super().__init__(parent,style = wx.SUNKEN_BORDER)
self.SetBackgroundColour('snow2')
List_choices = ["1Km","3Km"]
List2 = ["3X3","5X5","7X7"]
self.dateLbl = wx.StaticBox(self, -1, 'Outils ', size=(310, 320))
self.dategraphSizer = wx.StaticBoxSizer(self.dateLbl, wx.VERTICAL)
combobox1 = wx.ComboBox(self,choices = List_choices, size =(80,20),pos =(180,50))
combobox2 = wx.ComboBox(self,choices = List2, size =(80,20),pos =(180,90))
wx.StaticText(self, label='Referen:', pos=(70, 50))
wx.StaticText(self, label='pixel:', pos=(70, 90))
QuickLook = wx.Button(self ,-1, "Open file" , size =(80, 25),pos =(180,130))
wx.StaticText(self, label='QuickLook:', pos=(70, 130))
QuickLook.Bind(wx.EVT_BUTTON, self.onOpen)
def onOpen(self, event):
wildcard = "netCDF4 files (*.nc)|*.nc"
dialog = wx.FileDialog(self, "Open netCDF4 Files| HDF5 files", wildcard=wildcard,
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
if dialog.ShowModal() == wx.ID_CANCEL:
return
path = dialog.GetPath()
# panel for visualization
class LeftPanelBottom(wx.Panel):
def __init__(self, parent):
super().__init__(parent,style = wx.SUNKEN_BORDER)
self.SetBackgroundColour('whitesmoke')
self.dateLbl = wx.StaticBox(self, -1, 'QuickLook', size=(310, 600))
that it code for read and view netcdf4 in python3.6:
import numpy as np
import netCDF4
import matplotlib.pyplot as plt
#read the netcdf
fic='g_xvxvxvxv_20190108T120000Z.nc'
path='/home/globe/2019/01/08/'
nc = netCDF4.Dataset(path+fic,'r')
#read one variable in netcfd file
cm=nc.variables['cm'][:]
#visualization
plt.pcolormesh(cm)
plt.colorbar()
plt.show()
that what i would see in panel2 like quicklook:
[![enter image description here][1]][1]
what i would like to do is use my code to read the .nc in my code and that my users can just choose a file and then display automatically on the other panel2 :
[![enter image description here][2]][2]
maybe is like this example : How to use matplotlib blitting to add matplot.patches to an matplotlib plot in wxPython?
thank you for the help
Just open another frame and pass it the filename to be decoded, uncompressed, whatever, to be displayed.
The other option is to use webbrowser which will automatically pick the program required to display the file, based on the preferences that you have set on your pc.
import wx
import webbrowser
import numpy as np
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.select_button = wx.Button(panel, label="Select file")
sizer.Add(self.select_button, 0, 0, 0)
self.select_button.Bind(wx.EVT_BUTTON, self.pick_file)
self.load_options = "netCDF4 files (nc)|*.nc| Text files (txt) |*.txt| All files |*.*"
panel.SetSizer(sizer)
def pick_file(self, event):
with wx.FileDialog(self, "Pick files", wildcard=self.load_options,
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE) as fileDialog:
if fileDialog.ShowModal() != wx.ID_CANCEL:
chosen_file = fileDialog.GetPath()
if chosen_file.endswith('.txt'):
#Method 1 using another frame
QuickLook(parent=self, text=chosen_file)
elif chosen_file.endswith('.nc'):
QuickLook_plot(parent=self, text=chosen_file)
else:
#Method 2 (the smart method) using webbrowser which chooses the application
# to use to display the file, based on preferences on your machine
webbrowser.open_new(chosen_file)
class QuickLook(wx.Frame):
def __init__(self,parent,text=None):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Quick Look", size=(610,510))
panel = wx.Panel(self, wx.ID_ANY, size=(600,500))
log = wx.TextCtrl(panel, wx.ID_ANY,size=(600,480),
style = wx.TE_MULTILINE|wx.TE_READONLY|wx.VSCROLL)
Quit_button = wx.Button(panel, wx.ID_ANY, "&Quit")
Quit_button.Bind(wx.EVT_BUTTON, self.OnQuit)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(log, 1, wx.ALL|wx.EXPAND, 0)
sizer.Add(Quit_button,0,wx.ALIGN_RIGHT)
panel.SetSizerAndFit(sizer)
# use whatever method is appropriate for the file type
# to read, decode, uncompress, etc at this point
# I am assuming a text file below.
try:
with open(text,'rt') as f:
TextInfo = f.read()
log.write(TextInfo)
log.SetInsertionPoint(0)
self.Show()
except:
self.OnQuit(None)
def OnQuit(self,event):
self.Close()
self.Destroy()
class QuickLook_plot(wx.Frame):
def __init__(self, parent,text=None):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Quick Plot", size=(610,510))
panel = wx.Panel(self, wx.ID_ANY, size=(600,500))
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
self.canvas = FigureCanvas(panel, -1, self.figure)
Quit_button = wx.Button(panel, wx.ID_ANY, "&Quit")
Quit_button.Bind(wx.EVT_BUTTON, self.OnQuit)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.sizer.Add(Quit_button, 0,wx.ALIGN_RIGHT)
panel.SetSizerAndFit(self.sizer)
#plot figure
t = np.arange(0.0, 30.0, 0.01)
s = np.sin(2 * np.pi * t)
self.axes.plot(t, s)
self.Show()
def OnQuit(self,event):
self.Close()
self.Destroy()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'A test dialog')
frame.Show()
return True
if __name__ == "__main__":
app = MyApp()
app.MainLoop()
I am using PyQt5 to create a GUI program.
I have a problem when creating a label beside the QComboBox.
If I didnt create a label beside the QComboBox , it would look like the picture down below.
But if I added the label it would be like this :
The selection list just moved down a little bit automatically.
How can I do to make it be align to the label at the left-hand side?
(I mean just beside the CASE TYPE)
(I comment the critical part in my code)
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets
import xml.etree.cElementTree as ET
class App(QMainWindow):
def __init__(self,parent=None):
super().__init__()
self.title = "Automation"
self.left = 10
self.top = 10
self.width = 400
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
self.textbox.move(80, 20)
#self.textbox.resize(50,40)
self.textbox2 = QLineEdit(self)
self.textbox2.move(80, 80)
#self.textbox2.resize(50,40)
# Create text beside editor
wid1 = QWidget(self)
self.setCentralWidget(wid1)
mytext = QFormLayout()
mytext.addRow("CASE INDEX",self.textbox)
mytext.addRow("CASE TYPE",self.textbox2)
wid1.setLayout(mytext)
#################### Critical Part #######################
self.CB = QComboBox()
self.CB.addItems(["RvR","Turntable","Fixrate"])
self.CB.currentIndexChanged.connect(self.selectionchange)
label = QLabel("CASE TYPE")
mytext.addRow(label,self.CB) # this one makes the list shift down a little bit
mytext.addWidget(self.CB)
wid1.setLayout(mytext)
##########################################################
# Create a button in the window
self.button = QPushButton('Show text', self)
self.button.move(20,150)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.center()
self.show()
#pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
textboxValue2 = self.textbox2.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: "+ textboxValue + " , second msg is: " + textboxValue2, QMessageBox.Ok, QMessageBox.Ok)
print(textboxValue)
self.textbox.setText("")
self.textbox2.setText("")
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def selectionchange(self,i):
print ("Items in the list are :")
for count in range(self.CB.count()):
print (self.CB.itemText(count))
print ("Current index",i,"selection changed ",self.CB.currentText())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Please , I need your help.
Thanks.
Try it:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets
import xml.etree.cElementTree as ET
class App(QMainWindow):
def __init__(self,parent=None):
super().__init__()
self.title = "Automation"
self.left = 10
self.top = 10
self.width = 400
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
# self.textbox.move(80, 20)
#self.textbox.resize(50,40)
self.textbox2 = QLineEdit(self)
# self.textbox2.move(80, 80)
#self.textbox2.resize(50,40)
# Create text beside editor
wid1 = QWidget(self)
self.setCentralWidget(wid1)
mytext = QFormLayout()
mytext.addRow("CASE INDEX", self.textbox)
mytext.addRow("CASE TYPE", self.textbox2)
# wid1.setLayout(mytext)
#################### Critical Part #######################
self.CB = QComboBox()
self.CB.addItems(["RvR","Turntable","Fixrate"])
self.CB.currentIndexChanged.connect(self.selectionchange)
label = QLabel("CASE TYPE")
mytext.addRow(label, self.CB) # this one makes the list shift down a little bit
# mytext.addWidget(self.CB)
# wid1.setLayout(mytext)
##########################################################
# Create a button in the window
self.button = QPushButton('Show text', self)
# self.button.move(20,150)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
layoutV = QVBoxLayout(wid1) # + wid1 <<<========
layoutV.addLayout(mytext) # +
layoutV.addWidget(self.button, alignment=Qt.AlignLeft) # +
self.center()
self.show()
#pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
textboxValue2 = self.textbox2.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: "+ textboxValue + " , second msg is: " + textboxValue2, QMessageBox.Ok, QMessageBox.Ok)
print(textboxValue)
self.textbox.setText("")
self.textbox2.setText("")
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def selectionchange(self,i):
print ("Items in the list are :")
for count in range(self.CB.count()):
print (self.CB.itemText(count))
print ("Current index",i,"selection changed ",self.CB.currentText())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
this is my first post here and I haven't seen it anywhere so hopefully it is ok. I am trying to change the displayed image with a keyboard click (think slideshow). This is my code so far:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import os
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Document Analysis'
self.left = 30
self.top = 30
self.width = 640
self.height = 480
self.imagenumber=0
self.initUI()
def keyPressEvent(self, event):
key=event.key()
if key==Qt.Key_Right:
self.imagenumber=self.imagenumber+1
self.showimage(self.imagenumber)
self.show()
else:
super(self).keyPressEvent(event)
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.showimage(0)
self.show()
def showimage(self,imagenumber):
label = QLabel(self)
directory = "C:\\Desktop\\Pictures"
imagelist = os.listdir(directory)
pixmap = QPixmap(directory + '\\' + imagelist[imagenumber])
label.setPixmap(pixmap)
self.resize(pixmap.width() + 500, pixmap.height())
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
It seems to be sort of getting somewhere, the first image displays just fine, and I know imagenumber does change, and when I stopped it from showing at first it resized the window but still didn't show the image. Any suggestions on what I am doing wrong?
This is part of a larger project which is the reason for the extra space on the side of the picture, but help would be appreciated.
You're close. Try the following...
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import os
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Document Analysis'
self.left = 30
self.top = 30
self.width = 640
self.height = 480
self.imagenumber=0
self.initUI()
def keyPressEvent(self, event):
key=event.key()
if key==Qt.Key_Right:
self.imagenumber=self.imagenumber+1
self.showimage(self.imagenumber)
# self.show()
else:
super(self).keyPressEvent(event)
def initUI(self):
layout = QVBoxLayout()
self.setLayout(layout)
self.label = QLabel(self)
layout.addWidget(self.label)
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.showimage(0)
self.show()
def showimage(self,imagenumber):
# label = QLabel(self)
directory = "C:\\Desktop\\Pictures"
imagelist = os.listdir(directory)
pixmap = QPixmap(directory + '\\' + imagelist[imagenumber])
# label.setPixmap(pixmap)
self.label.setPixmap(pixmap)
self.resize(pixmap.width() + 500, pixmap.height())
# self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Mainly, you need a persistent label. You also only need to call show() once.