How to align a label with my selection list - python-3.x

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_())

Related

Get ID of dynamically created button when clicked

I have a program that dynamically creates tabs with buttons on them, when the user clicks button, I want it to give me the button_id (number that corresponds to the tab index).
I understand that you can do something like tabwidget.currentIndex() to get index of tab being used, but I don't want that as I will eventually have a method that iterates through the number of tabs and access each button without selecting the tabs as shown below.
for i in range(1,self.tabWidget.count()):
self.tabWidget.widget(i).stagematch.click()
For example:
If user clicks 'Clear Text' button on 'Tab 2' then I want it to give me the number 2 back.
How can I accomplish this without using the currentIndex() method for the tabs
Test code:
import sys
from PyQt5 import QtCore, QtWidgets
class TabPage(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
group = QtWidgets.QGroupBox('Monty Python')
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(group)
grid = QtWidgets.QGridLayout(group)
testbutton = QtWidgets.QPushButton('Clear Text')
grid.addWidget(testbutton, 2, 2)
testbutton.clicked.connect(self.tab_match)
#testbutton.clicked.connect(self.button_id)
def button_id(self):
sender = self.sender()
print(sender.text()) # Gives text of button, i'd like a number that corresponds to the tab# that called it
def tab_match(self,button_id):
#Do something with button ID here
pass
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.tabs = QtWidgets.QTabWidget()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
button = QtWidgets.QToolButton()
button.setToolTip('Add New Tab')
button.clicked.connect(self.addNewTab)
button.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_DialogYesButton))
self.tabs.setCornerWidget(button, QtCore.Qt.TopRightCorner)
self.addNewTab()
def addNewTab(self):
text = 'Tab %d' % (self.tabs.count() + 1)
self.tabs.addTab(TabPage(self.tabs), text)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5 import QtCore, QtWidgets
class TabPage(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent # +
self.button_id = 0 # +
group = QtWidgets.QGroupBox('Monty Python')
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(group)
grid = QtWidgets.QGridLayout(group)
testbutton = QtWidgets.QPushButton('Clear Text')
grid.addWidget(testbutton, 2, 2)
testbutton.clicked.connect(self.tab_match)
self.parent.currentChanged.connect(self.qtabwidget_currentchanged) # +
def tab_match(self):
#Do something with button ID here
print("\ndef tab_match: button_id-> {}".format(self.button_id)) # +
#QtCore.pyqtSlot(int)
def qtabwidget_currentchanged(self, index): # +
self.button_id = index
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.tabs = QtWidgets.QTabWidget()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
button = QtWidgets.QToolButton()
button.setToolTip('Add New Tab')
button.clicked.connect(self.addNewTab)
button.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_DialogYesButton))
self.tabs.setCornerWidget(button, QtCore.Qt.TopRightCorner)
self.button_id = 0
self.addNewTab()
def addNewTab(self):
text = 'Tab %d' % (self.tabs.count() + 1)
self.tabs.addTab(TabPage(self.tabs), text)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())

Python - showing next Tab by pressing a button

How can I change the Tab beeing shown by pressing an button ?
The function is beeing called by pressing a button in a message box.
I have tried setCurrentIndex() but the Tab beeing shown will not change.
I am using Python 3.6 and pyqt5.
Here is my Code:
import sys
from PyQt5 import QtWidgets, QtCore, QtPrintSupport, QtGui
from PyQt5.QtWidgets import *
class main_window(QTabWidget):
def __init__(self, parent=None):
super(QTabWidget, self).__init__(parent)
self.setGeometry(50, 50, 1100, 750)
self.setWindowTitle("Programm") #
self.centralWidget = QtWidgets.QWidget()
self.tabWidget = QtWidgets.QTabWidget(self.centralWidget)
self.tabWidget.setGeometry(QtCore.QRect(10, 10, 1200, 1000))
self.tabWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.West)
self.tab_v1 = QtWidgets.QWidget()
self.addTab(self.tab_v1, "Tab 1")
self.tab_v2 = QtWidgets.QWidget()
self.addTab(self.tab_v2, "Tab 2")
self.tab_v3 = QtWidgets.QWidget()
self.addTab(self.tab_v3, "Tab 3")
self.openFile = QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
self.openFile.clicked.connect(self.on_click_do)
def on_click_do(self):
box1 = QMessageBox()
box1.setIcon(QMessageBox.Question)
box1.setWindowTitle('Information')
box1.setText(
"Do you want to go to the next Tab?")
box1.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
buttonY = box1.button(QMessageBox.Yes)
buttonY.setText('Yes') ##translation
buttonN = box1.button(QMessageBox.No)
buttonN.setText('No') ## translation
box1.exec_()
if box1.clickedButton() == buttonN:
pass
elif box1.clickedButton() == buttonY:
self.tabWidget.setCurrentIndex(1)
def main():
app = QApplication(sys.argv)
ex = main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Try it:
import sys
from PyQt5 import QtWidgets, QtCore, QtPrintSupport, QtGui
from PyQt5.QtWidgets import *
class main_window(QTabWidget):
def __init__(self, parent=None):
super(QTabWidget, self).__init__(parent)
self.setGeometry(50, 50, 1100, 750)
self.setWindowTitle("Programm") #
self.centralWidget = QtWidgets.QWidget()
self.tabWidget = QtWidgets.QTabWidget(self.centralWidget)
self.tabWidget.setGeometry(QtCore.QRect(10, 10, 1200, 1000))
self.tabWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.West)
self.tab_v1 = QtWidgets.QWidget()
self.addTab(self.tab_v1, "Tab 1")
self.tab_v2 = QtWidgets.QWidget()
self.addTab(self.tab_v2, "Tab 2")
self.tab_v3 = QtWidgets.QWidget()
self.addTab(self.tab_v3, "Tab 3")
self.openFile = QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
self.openFile.clicked.connect(self.on_click_do)
def on_click_do(self):
box1 = QMessageBox()
box1.setIcon(QMessageBox.Question)
box1.setWindowTitle('Information')
box1.setText(
"Do you want to go to the next Tab?")
box1.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
buttonY = box1.button(QMessageBox.Yes)
buttonY.setText('Yes') ##translation
buttonN = box1.button(QMessageBox.No)
buttonN.setText('No') ## translation
box1.exec_()
if box1.clickedButton() == buttonN:
pass
elif box1.clickedButton() == buttonY:
#self.tabWidget.setCurrentIndex(1) # ---
self.setCurrentIndex(1) # +++
def main():
app = QApplication(sys.argv)
ex = main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Pyqt5 inheritance

full code: link to file
I'm trying to build a GUI using PyQT5, and I have two classes:
In the main class "Window", I have a method to close/exit the GUI, and when I use the method within the class, everything is working
class Window(QMainWindow):
choice = QMessageBox.question(self, ' WARNING!!!!', 'Are you sure to {}'.format(message),
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if choice == QMessageBox.Yes:
print('Quiting Application')
return sys.exit()
else:
pass
But the problem starts here, with the second class, when I try to quit using other class : Q_button.clicked.connect(Window.close_app)
class NewGrid(QWidget):
def __init__(self, parent=None):
super(NewGrid, self).__init__(parent)
grid = QGridLayout()
grid.addWidget(self.createExampleGroup(), 0, 0)
grid.addWidget(self.check_box_vBBU(), 21, 21)
grid.addWidget(self.button_test(), 0, 1)
grid.addWidget(self.quit_button(), 2, 2)
self.setLayout(grid)
def quit_button(self):
groupBox = QGroupBox("Quit_placeholder")
Q_button = QPushButton('Quit', self)
box = QHBoxLayout()
box.addWidget(Q_button)
super()
**Q_button.clicked.connect(Window.close_app)**
groupBox.setLayout(box)
return groupBox
any solution?
edit:
Here is the full code
import sys
from ctypes import windll
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
SCREEN_WIDTH = windll.user32.GetSystemMetrics(0) # 1920
SCREEN_HEIGHT = windll.user32.GetSystemMetrics(1) # 1080
class CustomDialog(QDialog):
def __init__(self, *args, **kwargs):
super(CustomDialog, self).__init__(parent=None)
Qbtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
self.buttonBox.accepted(self.accept)
self.buttonBox.rejected(self.reject)
self.layout = QVBoxLayout()
self.layout.addWidget(self.buttonBox)
self.setLayout(self.layout)
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3, SCREEN_WIDTH / 3,
SCREEN_HEIGHT / 2) # (start_point_X,start_point_Y,DIMensionX,DimensionY)
self.setWindowIcon(QIcon('dru_icon.png'))
self.setWindowTitle('----------------------DRU GUI-----------------')
self.statusBar()
self.file_menu()
self.view_menu()
self.toolbar_menu()
self.home()
def home(self):
# btn = QPushButton('quit', self)
# btn.clicked.connect(self.close_app)
# make the buttons near the bottom right: 1920-50=450, 1080-50=250
# btn.move(450, 250)
# btn.resize(50, 50)
# btn.move(SCREEN_WIDTH / 3 - 50, SCREEN_HEIGHT / 2 - 50)
label = QLabel("Holla")
label.setAlignment(Qt.AlignBottom)
self.setCentralWidget(label)
widget = NewGrid()
self.setCentralWidget(widget)
self.show()
def toolbar_menu(self):
toolbar = QToolBar("My Main Toolbar")
toolbar.setIconSize(QSize(32, 32)) # manual size
self.addToolBar(toolbar) # showing toolbar
icon1 = self.set_toolbar_icon('new_icon', icon_image='truck--plus')
icon1.triggered.connect(self.close_app)
icon2 = self.set_toolbar_icon('iconNum2')
# icon2.triggered.connect(self.notification_button)
icon3 = self.set_toolbar_icon('iconNum3', icon_image='application-monitor')
def set_toolbar_icon(self, icon_name="NONE", icon_image='animal-monkey.png', Width=32, Length=32):
toolbar = QToolBar("My Main Toolbar")
toolbar.setIconSize(QSize(Width, Length)) # manual size
self.addToolBar(toolbar) # showing toolbar
icon_name = QAction(QIcon(icon_image), icon_name, self)
# icon_name.triggered.connect(
# self.notification_button) # add different command later, for now its quitting,
self.toolBar = self.addToolBar('RUN IT')
# self.toolBar.addAction(icon1) #will be the default icon size from windows
toolbar.addAction(icon_name)
return icon_name
# ------main menu dialog --------
def file_menu(self):
# creating a toolbar with menu
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('File')
quit_tooltip = QAction('&Quit', self)
quit_tooltip.setShortcut('Ctrl+Q')
quit_tooltip.setToolTip('close the app')
# quit_tooltip.triggered.connect(self.close_app)
quit_tooltip.triggered.connect(self.close_app)
fileMenu.addAction(quit_tooltip)
def view_menu(self):
mainMenu = self.menuBar()
viewMenu = mainMenu.addMenu('View')
# ------main menu dialog --------
def notification_button(self):
return self.areYouSure_toolbar(message='NO ACTION DEFINED')
def close_app(self): # defined our own method of closing
# choice = QMessageBox.question(self, ' WARNING!!!!', 'Are you sure to quit?',
# QMessageBox.Yes | QMessageBox.No,
# QMessageBox.No) # the last QMessageBox.No is to highliht the option implicitly
choice = self.areYouSure_toolbar(message='Quit')
if choice == QMessageBox.Yes:
print('Quiting Application')
return sys.exit()
else:
pass
def areYouSure_toolbar(self, message='____'):
choice = QMessageBox.question(self, ' WARNING!!!!', 'Are you sure to {}'.format(message),
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No) # the last QMessageBox.No is to highliht the option implicitly
return choice
class NewGrid(QWidget):
def __init__(self, parent=None):
super(NewGrid, self).__init__(parent)
grid = QGridLayout()
grid.addWidget(self.createExampleGroup(), 0, 0)
grid.addWidget(self.check_box_vBBU(), 0, 1)
grid.addWidget(self.button_test(), 1, 0)
grid.addWidget(self.check_box_LPR(), 1, 1)
grid.addWidget(self.quit_button(), 3, 3)
# grid.addWidget(self.createExampleGroup(), 1, 2)
self.setLayout(grid)
# temp = Window()
# self.setWindowTitle("PyQt5 Group Box")
# self.resize(400, 300)
def check_box_vBBU(self):
groupBox = QGroupBox("Input (From vBBU) ")
checkbox1 = QCheckBox('Port {}'.format(1), self)
checkbox2 = QCheckBox('Port {}'.format(2), self)
check_box = QHBoxLayout()
check_box.addWidget(checkbox1)
check_box.addWidget(checkbox2)
check_box.addStretch(1)
groupBox.setLayout(check_box)
return groupBox
def check_box_LPR(self):
groupBox = QGroupBox("Output (from LPR) ")
layout = QHBoxLayout()
for n in range(20):
btn = QCheckBox('LPR' + str(n))
# btn.pressed.connect(self.close_app_Newgrid) #where to connect
layout.addWidget(btn)
# btn.setChecked(True)
num_of_buttons = n
# widget = QWidget()
selectRandom_btn = QPushButton('Random ports')
layout.addWidget(selectRandom_btn)
selectAll_btn = QPushButton('All')
selectAll_btn.pressed.connect(lambda : self.select_buttons(num_of_buttons, btn))
layout.addWidget(selectAll_btn)
groupBox.setLayout(layout)
return groupBox
def select_buttons(self, num_of_buttons,btn):
for x in range(1,num_of_buttons-1):
btn.setC
# btn[1].setChecked(True)
def quit_button(self):
groupBox = QGroupBox("Quit_placeholder")
Q_button = QPushButton('Quit', self)
box = QHBoxLayout()
box.addWidget(Q_button)
super()
# Q_button.clicked.connect(self.close_app_Newgrid)
# Q_button.clicked.connect(Window.close_app)
groupBox.setLayout(box)
return groupBox
def button_test(self):
groupBox = QGroupBox("test buttons")
btn1 = QPushButton("Push me", self)
# btn1.clicked.connect(self.close_app)# need to connect the button somewhere..
vbox = QHBoxLayout()
vbox.addWidget(btn1)
# vbox.addStretch(1)
groupBox.setLayout(vbox)
return groupBox
def createExampleGroup(self):
groupBox = QGroupBox("Data type")
radio1 = QRadioButton("Binary")
radio2 = QRadioButton("Decimal")
radio1.setChecked(True)
vbox = QVBoxLayout()
vbox.addWidget(radio1)
vbox.addWidget(radio2)
vbox.addStretch(1)
groupBox.setLayout(vbox)
return groupBox
def close_app_Newgrid(self): # defined our own method of closing
choice = QMessageBox.question(self, ' WARNING!!!!', 'Are you sure to quit?',
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No) # the last QMessageBox.No is to highliht the option implicitly
if choice == QMessageBox.Yes:
# print('Quiting Application')
return sys.exit()
else:
return
def run():
app = QApplication(sys.argv)
Gui = Window()
sys.exit(app.exec_())
run()
update :
I tried to simplify the solution below:
for w in QApplication.topLevelWidgets():
if isinstance(w,Window):
w = True
windows = w
The connection is between the signal of one object and the slot of another, not between classes, so the instruction is incorrect.
So in order to perform this task we must get some way to the Window object, a possible solution is to take advantage of Window is the window, so it is a top-Level for it we use the topLevelWidgets() method and we filter through isinstance():
def quit_button(self):
groupBox = QGroupBox("Quit_placeholder")
Q_button = QPushButton('Quit', self)
box = QHBoxLayout()
box.addWidget(Q_button)
#Q_button.clicked.connect(self.close_app_Newgrid)
windows = [w for w in QApplication.topLevelWidgets() if isinstance(w, Window)]
if windows:
Q_button.clicked.connect(windows[0].close_app)
groupBox.setLayout(box)
return groupBox
Note: the problem is not due to inheritance.

PyQt change picture with keyboard button

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.

QWidget cannot display on QMainWindow instance PyQt5

I am learning PyQt5 now and tried to do something little on my own. I have made a very basic custom toolbox, which has just 6 QPushButtons buttons on it, which inherits from QWidget class.
My problem is that I can't display my toolbox on my QMainWidow instance. Let me show you what I did;
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class ToolBox(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn = [QPushButton('B', self) for i in range(6)]
for Btn in btn:
Btn.resize(30, 30)
self.resize(60, 90)
k = 0
for i in range(6):
btn[i].move((i%2)*30, k*30)
k += 1 if i % 2 == 1 else 0
self.show()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(300, 200)
self.statusBar().showMessage('Ready!')
exitAction = QAction(QIcon('idea.png'), 'Exit', self)
exitAction.setStatusTip('Exit application')
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('File')
fileMenu.addAction(exitAction)
t = ToolBox()
t.move(150, 150)
t.show() #With and without this line, it doesn't work.
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
m = MainWindow()
sys.exit(app.exec_())
You just need to position your widget somewhere in the QMainWindow canvas. All you have to do is position it in the MainWindow. Just for an example, I use setCentralWidget() to position your QWidget.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class ToolBox(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn = [QPushButton('B', self) for i in range(6)]
for Btn in btn:
Btn.resize(30, 30)
self.resize(60, 90)
k = 0
for i in range(6):
btn[i].move((i%2)*30, k*30)
k += 1 if i % 2 == 1 else 0
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(300, 200)
self.statusBar().showMessage('Ready!')
exitAction = QAction(QIcon('idea.png'), 'Exit', self)
exitAction.setStatusTip('Exit application')
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('File')
fileMenu.addAction(exitAction)
t = ToolBox()
self.setCentralWidget(t)
if __name__ == '__main__':
app = QApplication(sys.argv)
m = MainWindow()
m.show()
sys.exit(app.exec_())

Resources