pyqt5 Is there a limit to loading widgets using clicked.connect? - python

I'm using the QPushButton to load the UI. First -> Jumin -> Department -> next -> next I want to create the UI in order. The problem is that I can not load the third Department into the QMainwindow window. I do not know why
When you create a widget in QVBoxLayout, it changes the size of the widget according to the wallpaper like wxpython layout (wx.all). Can not change the position (move) and size (resize) by automatic centering?
import sys
from PyQt5.QtWidgets import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.center_widget = QWidget()
self.setCentralWidget(self.center_widget)
self.FirstUI()
def FirstUI(self):
self.btn1 = QPushButton('test1', self)
self.btn1.move(50, 50)
self.btn1.clicked.connect(self.btn1_click)
def JuminUI(self):
self.ju1 = QLineEdit('13')
self.btn2 = QPushButton('^^^^^^^^^^')
self.ju_text = QLabel('asd')
self.jumim_layout = QVBoxLayout()
self.jumim_layout.addWidget(self.ju_text)
self.jumim_layout.addWidget(self.ju1)
self.jumim_layout.addWidget(self.btn2)
self.centralWidget().setLayout(self.jumim_layout)
self.btn2.clicked.connect(self.btn2_click)
def DepartmentUI(self):
self.depart_layout = QVBoxLayout()
self.depart_layout.addWidget(QPushButton('sdfsdf'))
self.centralWidget().setLayout(self.depart_layout)
def btn1_click(self):
self.btn1.deleteLater()
self.JuminUI()
def btn2_click(self):
self.ju1.deleteLater()
self.btn2.deleteLater()
self.ju_text.deleteLater()
self.DepartmentUI()
if __name__ == "__main__":
app = QApplication(sys.argv)
fream = MainWindow()
fream.show()
app.exec_()

creating and removing widgets is almost always a bad idea, and your code falls into those bad ideas, it's always best to hide the widgets and for that you should use the QStackedWidget, what QStackedWidget does is just make a widget visible on all widgets that you have been assigned by changing the currentIndex.
import sys
from functools import partial
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.center_widget = QtWidgets.QStackedWidget()
self.setCentralWidget(self.center_widget)
self.FirstUI()
self.JuminUI()
self.DepartmentUI()
def FirstUI(self):
widget = QtWidgets.QWidget()
self.btn1 = QtWidgets.QPushButton('test1', widget)
self.btn1.move(50, 50)
self.center_widget.addWidget(widget)
self.btn1.clicked.connect(partial(self.center_widget.setCurrentIndex, 1))
def JuminUI(self):
widget = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(widget)
self.ju1 = QtWidgets.QLineEdit('13')
self.btn2 = QtWidgets.QPushButton('^^^^^^^^^^')
self.ju_text = QtWidgets.QLabel('asd')
lay.addWidget(self.ju_text)
lay.addWidget(self.ju1)
lay.addWidget(self.btn2)
self.center_widget.addWidget(widget)
self.btn2.clicked.connect(partial(self.center_widget.setCurrentIndex, 2))
def DepartmentUI(self):
widget = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(widget)
lay.addWidget(QtWidgets.QPushButton('sdfsdf'))
self.center_widget.addWidget(widget)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
fream = MainWindow()
fream.show()
sys.exit(app.exec_())

Related

Common buttons and positioning in PyQt5's QStackedLayout

I am creating a Python PyQt5 app for a university project, which uses QStackedLayout to keep the app single-windowed.
First question: how can I create buttons that appear on every window and have the same function and property without having to recreate them in every window's UI setup (like in the code)?
Second question: after switching windows, how can I open the newly opened window at the previous's position? Right now they just open at the centre of the screen. I assume pos() or QPoint should be used but I can not figure out how.
import sys
from PyQt5.QtWidgets import (QApplication,
QMainWindow,
QPushButton,
QWidget,
QStackedLayout)
class Ui(QWidget):
def setupUi(self, Main):
self.application_width = 200
self.application_height = 200
self.stack = QStackedLayout()
self.window_1 = QWidget()
self.window_2 = QWidget()
self.window_1_UI()
self.window_2_UI()
self.stack.addWidget(self.window_1)
self.stack.addWidget(self.window_2)
def window_1_UI(self):
self.window_1.setFixedSize(self.application_width, self.application_height)
self.window_1.setWindowTitle("1")
'''REPLACE THIS BUTTON'''
self.window_1_button = QPushButton("Change window", self.window_1)
def window_2_UI(self):
self.window_2.setFixedSize(self.application_width, self.application_height)
self.window_2.setWindowTitle("2")
'''AND REPLACE THIS BUTTON'''
self.window_2_button = QPushButton("Change window", self.window_2)
class Main(QMainWindow, Ui):
def __init__(self):
super(Main, self).__init__()
self.setupUi(self)
self.window_1_button.clicked.connect(self.change_window)
self.window_2_button.clicked.connect(self.change_window)
def change_window(self):
if self.stack.currentIndex() == 0:
self.stack.setCurrentIndex(1)
else:
self.stack.setCurrentIndex(0)
if __name__ == "__main__":
app = QApplication(sys.argv)
M = Main()
sys.exit(app.exec())
Put your button outside your widgets (in your Main widget). The Ui class should manage the stacked layout.
For example:
class Ui(QWidget):
def setupUi(self, Main):
self.stack = QStackedLayout()
self.window_1 = QWidget()
self.window_2 = QWidget()
self.window_1_UI()
self.window_2_UI()
self.stack.addWidget(self.window_1)
self.stack.addWidget(self.window_2)
# Only one button
self.btn = QPushButton("Change window", self)
# Create the central widget of your Main Window
self.main_widget = QWidget()
layout = QVBoxLayout(self.main_widget)
layout.addLayout(self.stack)
layout.addWidget(self.btn)
self.setCentralWidget(self.main_widget)
self.btn.clicked.connect(self.change_window)
def change_window(self):
if self.stack.currentIndex() == 0:
self.stack.setCurrentIndex(1)
else:
self.stack.setCurrentIndex(0)
def window_1_UI(self):
label = QLabel("In Window 1", self.window_1)
def window_2_UI(self):
label = QLabel("In Window 2", self.window_2)
class Main(QMainWindow, Ui):
def __init__(self):
super(Main, self).__init__()
self.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
M = Main()
M.show()
sys.exit(app.exec())

Have QScrollArea react on wheelEvent, also in space taken up by children?

Consider this example:
#!/usr/bin/env python
import sys,os
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import Qt
class MainWindow(QtWidgets.QMainWindow):
class ScrollAreaWheel(QtWidgets.QScrollArea): # SO:9475772
def __init__(self, parent=None):
super(MainWindow.ScrollAreaWheel, self).__init__(parent)
self.parent = parent
def wheelEvent(self, event):
print("wheelEvent", event.angleDelta().y())
def __init__(self):
#~ self.do_init = QtCore.QEvent.registerEventType()
QtWidgets.QMainWindow.__init__(self)
self.setMinimumWidth(1000)
self.setMinimumHeight(400)
self.frame1 = QtWidgets.QFrame(self)
self.frame1.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame1layout = QtWidgets.QGridLayout(self.frame1)
self.frame1layout.setSpacing(0);
self.frame1layout.setContentsMargins(0,0,0,0);
self.frame1widget = QtWidgets.QWidget()
self.frame1widget.setLayout(QtWidgets.QGridLayout())
self.frame1layout.addWidget(self.frame1widget)
self.frame1scroll = MainWindow.ScrollAreaWheel(self) #QtWidgets.QScrollArea()
self.frame1scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.frame1scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.frame1widget.layout().addWidget(self.frame1scroll, 0, 0) #, Qt.AlignCenter)
#self.frame1scrolllayout = QtWidgets.QHBoxLayout(self.frame1scroll)
self.frame1scrolllayout = QtWidgets.QGridLayout(self.frame1scroll)
self.frame1scroll.setWidget(self.frame1scrolllayout.widget())
self.frame1scroll.setWidgetResizable(True)
self.frame1scroll.setAlignment(Qt.AlignCenter)
self.frame1label = QtWidgets.QLabel()
self.frame1scrolllayout.addWidget(self.frame1label, 0, 0, Qt.AlignCenter) ##
pixmap = QtGui.QPixmap(200, 100)
pixmap.fill(Qt.red)
self.frame1label.setPixmap(pixmap)
self.frame2 = QtWidgets.QFrame(self)
self.frame2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame2layout = QtWidgets.QHBoxLayout(self.frame2)
self.frame2layout.setSpacing(0);
self.frame2layout.setContentsMargins(0,0,0,0);
self.frame2scroll = QtWidgets.QScrollArea(self)
self.frame2scroll.setWidgetResizable(True)
self.frame2widget = QtWidgets.QWidget()
self.frame2widget.setLayout(QtWidgets.QGridLayout())
self.frame2scroll.setWidget(self.frame2widget)
self.frame2layout.addWidget(self.frame2scroll)
self.mainwid = QtWidgets.QWidget()
self.mainwid.setLayout(QtWidgets.QGridLayout())
self.setCentralWidget(self.mainwid)
self.splitter1 = QtWidgets.QSplitter(Qt.Horizontal)
self.splitter1.addWidget(self.frame1)
self.splitter1.addWidget(self.frame2)
self.splitter1.setSizes([600, 600]); # equal splitter at start
self.mainwid.layout().addWidget(self.splitter1)
self.mainwid.layout().update()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
main = MainWindow()
main.show()
sys.exit(app.exec_())
It generates this (Ubuntu 18.04):
I want to use mousewheel only on the left QScrollArea, for which I've made a separate class. However, its wheelEvent fires only when I'm outside the red box, not when I hover over it. How can I make ScrollAreaWheel.wheelEvent fire even when mouse is over the child label (the red box)?
You are the QLabel placing on top of the QScrollArea instead of placing it inside, visually it is the same but at the level of events it is not.
from PyQt5 import QtCore, QtGui, QtWidgets
class ScrollAreaWheel(QtWidgets.QScrollArea):
def wheelEvent(self, event):
print("wheelEvent", event.angleDelta().y())
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setMinimumSize(1000, 400)
frame1 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.StyledPanel)
scrollarea1 = ScrollAreaWheel(widgetResizable=True)
scrollarea1.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scrollarea1.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
widget1 = QtWidgets.QWidget()
scrollarea1.setWidget(widget1)
label_lay = QtWidgets.QGridLayout(widget1)
lay1 = QtWidgets.QVBoxLayout(frame1)
lay1.addWidget(scrollarea1)
pixmap = QtGui.QPixmap(200, 100)
pixmap.fill(QtCore.Qt.red)
label = QtWidgets.QLabel(pixmap=pixmap)
label_lay.addWidget(label, 0, 0, QtCore.Qt.AlignCenter)
#==============================
frame2 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.StyledPanel)
scrollarea2 = QtWidgets.QScrollArea(widgetResizable=True)
scrollarea2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scrollarea2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
widget2 = QtWidgets.QWidget()
scrollarea2.setWidget(widget2)
splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
splitter.addWidget(frame1)
splitter.addWidget(frame2)
splitter.setSizes([600, 600])
self.setCentralWidget(splitter)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())

QScrollArea.ensureWidgetVisible method does not show target widget

I am trying to make the last QPushButton visible by using method QScrollArea().ensureWidgetVisible(), but as you can see this method doesn't scroll till the last QPushButton.
Example
Could you please assist and solve my issue perhaps issue with setFrameStyle? thank you in advance.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Widget(QWidget):
def __init__(self, parent= None):
super(Widget, self).__init__()
self.setFixedHeight(200)
#Container Widget
widget = QWidget()
#Layout of Container Widget
layout = QVBoxLayout(self)
for _ in range(20):
btn = QPushButton("test")
layout.addWidget(btn)
widget.setLayout(layout)
#Scroll Area Properties
scroll = QScrollArea()
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll.setWidgetResizable(False)
scroll.setWidget(widget)
# print(scroll.verticalScrollBar().maximum())
# vbar = scroll.verticalScrollBar()
# vbar.setValue(vbar.maximum())
#vbar.setValue(vbar.maximum())
#Scroll Area Layer add
vLayout = QVBoxLayout(self)
vLayout.addWidget(scroll)
self.setLayout(vLayout)
# items = (layout.itemAt(i) for i in range(layout.count()))
# for w in items:
# print(w)
print(layout.count())
#scroll.ensureWidgetVisible(layout.itemAt(layout.count()-5).widget(), xMargin=10, yMargin=10 )
scroll.ensureWidgetVisible(layout.itemAt(layout.count()-1).widget() )
print(layout.itemAt(layout.count()-1).widget(),"last widget")
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = Widget()
dialog.show()
app.exec_()
The problem is that for efficiency reasons widgets sizes are not calculated or updated until they are displayed, in your case the viewport of QScrollArea has not updated its size and therefore moves the scroll to an intermediate position. A possible solution is to use QTimer::singleShot() to call the function ensureWidgetVisible() a moment after it has been displayed:
import sys
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent= None):
super(Widget, self).__init__(parent)
self.setFixedHeight(200)
#Container Widget
widget =QtWidgets.QWidget()
#Layout of Container Widget
layout = QtWidgets.QVBoxLayout(widget)
for _ in range(20):
btn = QtWidgets.QPushButton("test")
layout.addWidget(btn)
scroll = QtWidgets.QScrollArea()
scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
scroll.setWidgetResizable(False)
scroll.setWidget(widget)
#Scroll Area Layer add
vLayout = QtWidgets.QVBoxLayout(self)
vLayout.addWidget(scroll)
last_widget = layout.itemAt(layout.count()-1).widget()
QtCore.QTimer.singleShot(0, partial(scroll.ensureWidgetVisible, last_widget))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
dialog = Widget()
dialog.show()
sys.exit(app.exec_())
or simply call show() before:
...
last_widget = layout.itemAt(layout.count()-1).widget()
self.show()
scroll.ensureWidgetVisible(last_widget)

PyQt5 QScrollArea widget with dynamically created GroupBoxes

I'm trying to make a toolbox widget that will do various different things. But I'm having trouble with the layout management regarding the QScrollArea. Following the stripped version of the code I have:
from PyQt5 import QtWidgets
import sys
class MyScrollWidget(QtWidgets.QWidget):
def __init__(self):
super(MyScrollWidget, self).__init__()
scrollArea = QtWidgets.QScrollArea(self)
top_widget = QtWidgets.QWidget()
top_layout = QtWidgets.QVBoxLayout()
for i in range(10):
group_box = QtWidgets.QGroupBox()
group_box.setTitle('GroupBox For Item {0}'.format(i))
layout = QtWidgets.QHBoxLayout(group_box)
label = QtWidgets.QLabel()
label.setText('Label For Item {0}'.format(i))
layout.addWidget(label)
push_button = QtWidgets.QPushButton(group_box)
push_button.setText('Run Button')
push_button.setFixedSize(100, 32)
layout.addWidget(push_button)
group_box.setLayout(layout)
top_layout.addWidget(group_box)
top_widget.setLayout(top_layout)
scrollArea.setWidget(top_widget)
self.resize(200, 500)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
widget = MyScrollWidget()
widget.show()
sys.exit(app.exec_())
But this only gives me a small fixed subsection of the widget that scrolled. But what I really wants is the whole widget to be scrollable if the widget/window is smaller than the total size of all the group boxes. I.e I'd like the widget to be used as if it was all fixed width, but if the user resized the widget smaller than that, it would scroll appropriately. I've tried various different methods with no good results so now I'm deferring to those who have more experience with layout management than I. Thank you for your time.
You have to set the scrollArea to MyScrollWidget using a layout.
from PyQt5 import QtWidgets
import sys
class MyScrollWidget(QtWidgets.QWidget):
def __init__(self):
super(MyScrollWidget, self).__init__()
lay = QtWidgets.QVBoxLayout(self)
scrollArea = QtWidgets.QScrollArea()
lay.addWidget(scrollArea)
top_widget = QtWidgets.QWidget()
top_layout = QtWidgets.QVBoxLayout()
for i in range(10):
group_box = QtWidgets.QGroupBox()
group_box.setTitle('GroupBox For Item {0}'.format(i))
layout = QtWidgets.QHBoxLayout(group_box)
label = QtWidgets.QLabel()
label.setText('Label For Item {0}'.format(i))
layout.addWidget(label)
push_button = QtWidgets.QPushButton(group_box)
push_button.setText('Run Button')
push_button.setFixedSize(100, 32)
layout.addWidget(push_button)
top_layout.addWidget(group_box)
top_widget.setLayout(top_layout)
scrollArea.setWidget(top_widget)
self.resize(200, 500)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
widget = MyScrollWidget()
widget.show()
sys.exit(app.exec_())

How to focus view on QLabel

I want to find QLabel with specific text and focus view on it. Finding widget with desired text is easy, but I couldn't figure out how to focus view on it.
The code so far looks like this:
import sys
from PySide import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super().__init__()
widget = QtGui.QWidget()
self.layout = QtGui.QGridLayout()
for i in range(10):
label = QtGui.QLabel("aaaa" + str(i))
self.layout.addWidget(label, i, 0)
widget.setLayout(self.layout)
self.toolbar = self.addToolBar("aa")
findAction = QtGui.QAction('Find', self)
findAction.triggered.connect(self.find)
self.toolbar.addAction(findAction)
self.scroll = QtGui.QScrollArea()
self.scroll.setWidget(widget)
self.scroll.setWidgetResizable(True)
self.setMaximumSize(200, 200)
self.setCentralWidget(self.scroll)
def find(self):
widgets = (self.layout.itemAt(i).widget() for i in range(self.layout.count()))
for w in widgets:
if isinstance(w, QtGui.QLabel):
if w.text() == "aaaa9":
w.setFocus()
def main():
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
app.exec_()
if __name__ == "__main__":
main()
Any ideas how to get focus working?
You can use ensureWidgetVisible()
self.scroll.ensureWidgetVisible(w)

Categories

Resources