Resizing QDialog after removing QWidget - python-3.x

Is there any way by which I can resize a QDialog after removing a QWidget from its layout?
I'm still a beginner so bear with me if the code looks a bit silly.
The main dialog geometry is stored during the resizeEvent()
Before creating the widget:
https://imgur.com/a/vFORp4t
When the widget is created:
https://imgur.com/z7KUa3I
When the widget is removed:
https://imgur.com/KdzULUe
def resizeEvent(self, event):
QtWidgets.QMainWindow.resizeEvent(self, event)
window = self.window()
self.dialog_rect = window.geometry()
self.DialogSizeChanged.emit() # pylint: disable=E1101
Here's the "create widget" code:
def create_info_widget(self):
px = self.dialog_rect.x()
py = self.dialog_rect.y()
w = self.dialog_rect.width()
h = self.dialog_rect.height()
self.dialog_stored_rect = self.dialog_rect
self.info_wdg = abw.ThumbnailInfo("Asset Info")
self.asset_wdg_layout.addWidget(self.info_wdg)
data = self.list_wdg.get_list_thumbnails_data()
path = data['thumbnail']
self.info_wdg.set_info_thumbnail(path)
wdg_h = self.info_wdg.height()
self.setGeometry(px, py, w, h + wdg_h)
self.updateGeometry()
And the "remove widget" code:
def remove_info_widget(self):
wdg = self.findChild(QtWidgets.QFrame, "Asset Info")
if wdg:
self.asset_wdg_layout.removeWidget(wdg)
wdg.deleteLater()
self.info_wdg = None
self.setGeometry(self.dialog_stored_rect)
self.updateGeometry()
As shown on grabbed images, when the widget is removed, it doesn't get back to its size before it was created.
Thank you,
Jacques.

We will first resize it and then use adjustSize to let QApplication know.
We are using resize for just resizing, not for fixed values
Make sure not to apply this when maximized
from PySide2.QtWidgets import (
QApplication,
QPushButton,
QWidget,
QVBoxLayout
)
class Test(QWidget):
def __init__(self):
super().__init__()
self.setLayout(QVBoxLayout(self))
self.add = QPushButton(self, text="Toggle")
self.added = QPushButton(self, text="Hello There")
self.added.setMinimumHeight(600)
self.added.setVisible(False)
self.layout().addWidget(self.add)
self.layout().addWidget(self.added)
self.add.clicked.connect(
lambda: self.added.setVisible(not self.added.isVisible())
)
self.add.clicked.connect(self.toggle)
# trick is to use resize and self.adjustSize
def toggle(self):
if self.isMaximized():
return ...
self.resize(self.width(), 600 if self.added.isVisible() else 100)
self.adjustSize()
sample = QApplication([])
test = Test()
test.show()
sample.exec_()

Related

How to make a layout with only aboslute positioning in pyqt

I want to make a layout where the user is able to move the widget inside freely with no constraints of rows or column. So I'm using absolute positioning. I'm able to make it happen in a window with no layout but I don't know what to use as a layout , problem is in the commented line in the code.
from PyQt5.QtWidgets import QWidget, QLabel, QApplication,QVBoxLayout,QHBoxLayout
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
class DragLabel(QLabel):
def mouseMoveEvent(self, e):
if e.buttons() == Qt.LeftButton:
drag = QDrag(self)
mime = QMimeData()
drag.setMimeData(mime)
drag.exec_(Qt.MoveAction)
class Window(QWidget):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.label = DragLabel('first', self)
self.label2 = DragLabel('second', self)
self.label3 = DragLabel('third', self)
self.label.move(50, 50)
self.label2.move(100, 100)
self.label3.move(150, 150)
# self.main_frame=QHBoxLayout()
# self.classic_frame=QVBoxLayout()
#what should I use here to make a frame working with absolute position only
# self.absolute_frame = ???
# self.absolute_frame.addWidget(self.label)
# self.absolute_frame.addWidget(self.label2)
# self.absolute_frame.addWidget(self.label3)
# self.main_frame.addLayout(self.classic_frame)
# self.main_frame.addLayout(self.absolute_frame)
# self.setLayout(self.main_frame)
def dragEnterEvent(self, e):
widget = e.source()
if isinstance(widget,DragLabel):
e.accept()
def dropEvent(self, e):
pos = e.pos()
widget_dep = e.source()
if isinstance(widget_dep,DragLabel):
widget_dep_name = widget_dep.text()
print(widget_dep_name)
widget_dep.move(pos.x(),pos.y())
if __name__ == '__main__':
app = QApplication([])
w = Window()
w.show()
app.exec_()

How to modify this PyQt5 current setup to enable drag resize between layouts

How to modify this current setup to enable resizing(horizontally and vertically) between the layouts shown below? Let's say I want to resize the lists in the right toward the left by dragging them using the mouse, I want the image to shrink and the lists to expand and same applies for in between the 2 lists.
Here's the code:
from PyQt5.QtWidgets import (QMainWindow, QApplication, QDesktopWidget, QHBoxLayout, QVBoxLayout, QWidget,
QLabel, QListWidget)
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import sys
class TestWindow(QMainWindow):
def __init__(self, left_ratio, right_ratio, window_title):
super().__init__()
self.left_ratio = left_ratio
self.right_ratio = right_ratio
self.current_image = None
self.window_title = window_title
self.setWindowTitle(self.window_title)
win_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
win_rectangle.moveCenter(center_point)
self.move(win_rectangle.topLeft())
self.tools = self.addToolBar('Tools')
self.left_widgets = {'Image': QLabel()}
self.right_widgets = {'List1t': QLabel('List1'), 'List1l': QListWidget(),
'List2t': QLabel('List2'), 'List2l': QListWidget()}
self.central_widget = QWidget(self)
self.main_layout = QHBoxLayout()
self.left_layout = QVBoxLayout()
self.right_layout = QVBoxLayout()
self.adjust_widgets()
self.adjust_layouts()
self.show()
def adjust_layouts(self):
self.main_layout.addLayout(self.left_layout, self.left_ratio)
self.main_layout.addLayout(self.right_layout, self.right_ratio)
self.central_widget.setLayout(self.main_layout)
self.setCentralWidget(self.central_widget)
def adjust_widgets(self):
self.left_layout.addWidget(self.left_widgets['Image'])
self.left_widgets['Image'].setPixmap(QPixmap('test.jpg').scaled(500, 400, Qt.IgnoreAspectRatio,
Qt.SmoothTransformation))
for widget in self.right_widgets.values():
self.right_layout.addWidget(widget)
if __name__ == '__main__':
test = QApplication(sys.argv)
test_window = TestWindow(6, 4, 'Test')
sys.exit(test.exec_())
One way to rescale the image to an arbitrary size while maintaining its aspect ratio is to subclass QWidget and override sizeHint and paintEvent and use that instead of a QLabel for displaying the image, e.g.
class PixmapWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self._pixmap = None
def sizeHint(self):
if self._pixmap:
return self._pixmap.size()
else:
return QSize()
def setPixmap(self, pixmap):
self._pixmap = pixmap
self.update()
def paintEvent(self, event):
painter = QPainter(self)
super().paintEvent(event)
if self._pixmap:
size = self._pixmap.size().scaled(self.size(), Qt.KeepAspectRatio)
offset = (self.size() - size)/2
rect = QRect(offset.width(), offset.height(), size.width(), size.height())
painter.drawPixmap(rect, self._pixmap)
Since you are subclassing QMainWindow you could use DockWidgets to display the lists instead of adding them to the layout of the central widget, e.g.
class TestWindow(QMainWindow):
def __init__(self, left_ratio, right_ratio, window_title):
super().__init__()
#self.left_ratio = left_ratio <--- not needed since image and lists
#self.right_ratio = right_ratio <--- are not sharing a layout anymore
...
# use PixmapWidget instead of QLabel for showing image
# refactor dictionary for storing lists to make adding DockWidgets easier
self.left_widgets = {'Image': PixmapWidget()}
self.right_widgets = {'List1': QListWidget(),
'List2': QListWidget()}
self.central_widget = QWidget(self)
# self.main_layout = QHBoxLayout() <-- not needed anymore
self.left_layout = QVBoxLayout()
self.adjust_widgets()
self.adjust_layouts()
self.show()
def adjust_layouts(self):
self.central_widget.setLayout(self.left_layout)
self.setCentralWidget(self.central_widget)
def adjust_widgets(self):
self.left_layout.addWidget(self.left_widgets['Image'])
self.left_widgets['Image'].setPixmap(QPixmap('test.jpg').scaled(500, 400, Qt.IgnoreAspectRatio, Qt.SmoothTransformation))
self.dock_widgets = []
for text, widget in self.right_widgets.items():
dock_widget = QDockWidget(text)
dock_widget.setFeatures(QDockWidget.NoDockWidgetFeatures)
dock_widget.setWidget(widget)
self.addDockWidget(Qt.RightDockWidgetArea, dock_widget)
self.dock_widgets.append(dock_widget)
Screenshots
You need to use QSplitter.
It acts almost like a box layout, but has handles that allow the resizing of each item.
Be aware that you can only add widgets to a QSplitter, not layouts, so if you need to add a "section" (a label and a widget) that can resize its contents, you'll have to create a container widget with its own layout.
Also note that using dictionaries for these kind of things is highly discouraged. For versions of Python older than 3.7, dictionary order is completely arbitrary, and while sometimes it might be consistent (for example, when keys are integers), it usually isn't: with your code some times the labels were put all together, sometimes the widgets were inverted, etc., so if somebody is using your program with <=3.6 your interface won't be consistent. Consider that, while python 3.6 will reach end of life in 2022, it's possible that even after that a lot of people will still be using previous versions.
If you need a way to group objects, it's better to use a list or a tuple, as I did in the following example.
If you really "need" to use a key based group, then you can use OrderedDict, but it's most likely that there's just something wrong with the logic behind that need to begin with.
class TestWindow(QMainWindow):
def __init__(self, left_ratio, right_ratio, window_title):
super().__init__()
self.left_ratio = left_ratio
self.right_ratio = right_ratio
self.current_image = None
self.window_title = window_title
self.setWindowTitle(self.window_title)
win_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
win_rectangle.moveCenter(center_point)
self.move(win_rectangle.topLeft())
self.tools = self.addToolBar('Tools')
self.left_widgets = {'Image': QLabel()}
self.right_widgets = [(QLabel('List1'), QListWidget()),
(QLabel('List2'), QListWidget())]
self.central_widget = QSplitter(Qt.Horizontal, self)
self.setCentralWidget(self.central_widget)
self.right_splitter = QSplitter(Qt.Vertical, self)
self.adjust_widgets()
self.central_widget.setStretchFactor(0, left_ratio)
self.central_widget.setStretchFactor(1, right_ratio)
self.show()
def adjust_widgets(self):
self.central_widget.addWidget(self.left_widgets['Image'])
self.left_widgets['Image'].setPixmap(QPixmap('test.jpg').scaled(500, 400, Qt.IgnoreAspectRatio,
Qt.SmoothTransformation))
self.left_widgets['Image'].setScaledContents(True)
self.central_widget.addWidget(self.right_splitter)
for label, widget in self.right_widgets:
container = QWidget()
layout = QVBoxLayout(container)
layout.addWidget(label)
layout.addWidget(widget)
self.right_splitter.addWidget(container)

QGraphicsview + scene + QGroupBox movement issue

For past few days I was trying to solve the issue of widget movement. At some point I tried rewriting QComboBox classes with mouse signals but that did not work. As a work around I settled for parenting my widget to a QGraphicsWidget but once I try to add another item it does not display any more and I'm not sure what to do. Here is full test script:
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication,QGraphicsItem, QGraphicsView, QGraphicsScene, QDesktopWidget, QCheckBox, QGroupBox, QPushButton, QGridLayout, QLabel, QLineEdit, QComboBox, QFont, QRadioButton, QButtonGroup, QWidget, QShortcut, QKeySequence, QIcon, QListView, QStandardItemModel, QStandardItem, QAction, QIntValidator, QListWidget, QProgressBar, QSpacerItem
from PyQt4.QtCore import QRect
from functools import partial
import sys
class node_GUI(QtGui.QWidget):
def __init__(self):
super(node_GUI, self).__init__()
class Main(QtGui.QMainWindow):
def __init__(self, *args):
super(Main, self).__init__(*args)#QtGui.QMainWindow.__init__(self)
self.init_defaults()
def init_defaults(self):
self.setGeometry(800,800,500,200)
self.lay_main = QGridLayout()
self.centralwidget = QtGui.QWidget()
self.centralwidget.setLayout(self.lay_main)
self.setCentralWidget(self.centralwidget)
btn_create_node = QPushButton("Create Node View")
btn_create_node.clicked.connect(self.create_node_view)
self.lay_main.addWidget(btn_create_node)
def showWindow(self,window):
window.show()
def printTest(self):
print "Start"
box = QGroupBox("subWidget")
box_btn = QPushButton("Test")
box_btn.clicked.connect(self.printTest)
le_edit = QLineEdit()
lay = QGridLayout()
box.setLayout(lay)
lay.addWidget(box_btn)
lay.addWidget(le_edit)
area = QtGui.QGraphicsWidget()
area.setMinimumSize(QtCore.QSizeF(400,300))
area.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
area.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
proxy = self.scene.addWidget(box)
proxy.setParentItem(area)
print "END"
def create_node_view(self):
print "creting node view"
window = node_GUI()
window.setGeometry(QRect(100, 100, 400, 200))
window.setWindowTitle("node ")
window.setObjectName("node")
show_window = QPushButton("Show Node Editor")
show_window.setObjectName("btn")
show_window.clicked.connect(partial(self.showWindow,window))
self.lay_main.addWidget(show_window)
box = QGroupBox("Widgets")
box_btn = QPushButton("Test")
box_btn.clicked.connect(self.printTest)
le_edit = QLineEdit()
lay = QGridLayout()
box.setLayout(lay)
lay.addWidget(box_btn)
lay.addWidget(le_edit)
area = QtGui.QGraphicsWidget()
area.setMinimumSize(QtCore.QSizeF(300,300))
area.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
area.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
area.setAutoFillBackground(True)
ecs = QtGui.QGraphicsEllipseItem()
ecs.setRect(QtCore.QRectF(79,79,79,79))
ecs.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
ecs.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
view = QGraphicsView()
self.scene = QGraphicsScene()
self.scene.addItem(area)
proxy = self.scene.addWidget(box)
proxy.setParentItem(area)
self.scene.addItem(ecs)
view.setScene(self.scene)
lay_window = QGridLayout()
window.setLayout(lay_window)
lay_window.addWidget(view)
def main():
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
When you click on Create Node View > Show Node Editor > Test button > a new GroupBox should appear but that does not work. Not sure why.
Right so I stopped using QGraphicsWidget() and instead I just use QGraphicsRectItem(ecs for example) once I did that change everything started to work as expected.

PyQt4 Mdi sub window not resizing properly

In the following example, when you click the button, the entire form is rebuilt adding a new label each time. At the end is a resize call that doesn't appear to work. While debugging, I validated the sizeHint() is returning the correct dimensions, and internally the widget thinks it is the correct size, but what is drawn is not correct. What can I do to force the MDI window to resize correctly? Also of note, when not sized correctly, if you manually start resizing, it suddenly snaps to the appropriate size.
import sys
import os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import PyQt4.Qt
class MdiWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.count = 0
self.buildWindow()
def buildWindow(self):
main = QVBoxLayout()
button = QPushButton('Change Count')
button.clicked.connect(self.changeCount)
main.addWidget(button)
for i in range(self.count):
main.addWidget(QLabel(str(i)))
widget = QWidget()
widget.setLayout(main)
self.setCentralWidget(widget)
self.resize(main.sizeHint())
def changeCount(self, event):
self.count += 1
self.buildWindow()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Resize Test')
self.mdiArea = QMdiArea()
self.setCentralWidget(self.mdiArea)
child = MdiWindow()
self.mdiArea.addSubWindow(child)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())

How can I make PyQt QSplitter visible?

Can I define the width/height for a QSplitter object? Can I make it visible with a proper arrow?
In my C++ code, I use QSplitter::setHandleWidth()
Adjusting the height would probably require adjusting the height of the container itself.
Here's how you can overwrite the QSplitter class to make the splitters to have some icon to let user know they can resize the widgets, See the image for output.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class Handle(QWidget):
def paintEvent(self, e=None):
painter = QPainter(self)
painter.setPen(Qt.NoPen)
painter.setBrush(Qt.Dense6Pattern)
painter.drawRect(self.rect())
class customSplitter(QSplitter):
def addWidget(self, wdg):
super().addWidget(wdg)
self.width = self.handleWidth()
l_handle = Handle()
l_handle.setMaximumSize(self.width*2, self.width*10)
layout = QHBoxLayout(self.handle(self.count()-1))
layout.setSpacing(0)
layout.setContentsMargins(0,0,0,0)
layout.addWidget(l_handle)
class Window(QMainWindow):
def setUI(self, MainWindow):
self.splt_v = customSplitter(Qt.Vertical)
self.splt_v.setHandleWidth(8)
self.splt_v.addWidget(QGroupBox("Box 1"))
self.splt_v.addWidget(QGroupBox("Box 2"))
self.splt_v.addWidget(QGroupBox("Box 3"))
self.wdg = QWidget()
self.v_lt = QVBoxLayout(self.wdg)
self.v_lt.addWidget(self.splt_v)
self.spl_h = customSplitter()
self.spl_h.addWidget(self.wdg)
self.spl_h.addWidget(QGroupBox("Box 4"))
self.spl_h.addWidget(QGroupBox("Box 5"))
self.h_lt = QHBoxLayout()
self.h_lt.addWidget(self.spl_h)
self.w = QWidget()
self.w.setLayout(self.h_lt)
self.w.setGeometry(0,0,1280,720)
self.w.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = Window()
ui.setUI(MainWindow)
sys.exit(app.exec_())

Resources