PySide crashing when replacing rows in QFormLayout - qt

Using the following code example PySide segfaults when pushing "Add", "Add", "Remove", "Add" and due to some other sequences of interaction.
Python: 2.7.6
PySide: 1.2.1
QtCore: 4.8.5
Code:
from PySide.QtGui import *
from PySide.QtCore import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setObjectName('MainWindow')
self.baseLayout = QWidget(self)
self.v_layout = QVBoxLayout(self.baseLayout)
self.setCentralWidget(self.baseLayout)
self.form_layout = QFormLayout(self.baseLayout)
self.v_layout.addLayout(self.form_layout)
self.button_add = QPushButton(self.baseLayout)
self.button_add.setText("Add")
self.v_layout.addWidget(self.button_add)
self.button_del = QPushButton(self.baseLayout)
self.button_del.setText("Remove")
self.v_layout.addWidget(self.button_del)
self.button_add.clicked.connect(self.add)
self.button_del.clicked.connect(self.remove)
self.fields = []
def add_item(self):
layout = QHBoxLayout(self.parent())
line = QLineEdit(self.parent())
slider = QSlider(self.parent())
layout.addWidget(line)
layout.addWidget(slider)
self.fields.append((layout, line, slider))
self.form_layout.addRow("Test", layout)
def add(self):
for i in range(15):
self.add_item()
def remove(self):
for (layout, line, slider) in self.fields:
line.deleteLater()
slider.deleteLater()
while self.form_layout.itemAt(0):
child = self.form_layout.takeAt(0)
if child.widget():
child.widget().deleteLater()
self.form_layout.update()
self.fields = []
def main():
import sys
app = QApplication(sys.argv)
frame = MainWindow()
frame.show()
app.exec_()
if __name__ == '__main__':
main()
Is this the correct way of adding compound widgets (in this case a QLineEdit and a QSlider within a QVBoxLayout) to a form layout? What am I doing wrong?

The correct way of adding "compound widgets" to a QFormLayout is to create a QWidget that will be the parent to that layout.
add_item() should rather look something like this:
def add_item(self):
widget = QWidget(self.parent())
layout = QHBoxLayout(widget)
line = QLineEdit(widget)
slider = QSlider(widget)
layout.addWidget(line)
layout.addWidget(slider)
self.fields.append((layout, widget, line, slider))
self.form_layout.addRow("Test", widget)
(And the widget also has to be removed when deleting the fields).

I think you are not creating the layouts in the right way, for example you are trying to set the layout of base_layout two times. Also you can check for count() on a QLayout to see if it has children:
from PySide.QtGui import *
from PySide.QtCore import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.baseLayout = QWidget(self)
self.v_layout = QVBoxLayout(self.baseLayout)
self.setCentralWidget(self.baseLayout)
self.form_layout = QFormLayout()
self.v_layout.addLayout(self.form_layout)
self.button_add = QPushButton()
self.button_add.setText("Add")
self.v_layout.addWidget(self.button_add)
self.button_del = QPushButton()
self.button_del.setText("Remove")
self.v_layout.addWidget(self.button_del)
self.button_add.clicked.connect(self.add)
self.button_del.clicked.connect(self.remove)
self.fields = []
def add_item(self):
layout = QHBoxLayout()
line = QLineEdit()
slider = QSlider()
layout.addWidget(line)
layout.addWidget(slider)
self.fields.append((layout, line, slider))
self.form_layout.addRow("Test", layout)
def add(self):
for i in range(15):
self.add_item()
def remove(self):
while self.form_layout.count() > 0:
child = self.form_layout.takeAt(0)
widget = child.widget()
if widget:
widget.deleteLater()
self.form_layout.update()
self.fields = []
def main():
import sys
app = QApplication(sys.argv)
frame = MainWindow()
frame.show()
app.exec_()
if __name__ == '__main__':
main()

Related

qt: qlayout do not correctly add widget

I want do dynamically change the layout in Qt. For example, I want to change the QHBoxLayout to QVBoxLayout through a button. My test code is:
from PyQt5.QtWidgets import *
import sys
class SubWidget(QWidget):
def __init__(self):
super().__init__()
self.lay = QHBoxLayout()
self.label1 = QLabel('left')
self.label2 = QLabel('right')
self.lay.addWidget(self.label1)
self.lay.addWidget(self.label2)
self.setLayout(self.lay)
def change(self):
self.lay.removeWidget(self.label1)
self.lay.removeWidget(self.label2)
self.lay = QVBoxLayout()
self.setLayout(self.lay)
self.lay.addWidget(self.label2)
self.lay.addWidget(self.label1)
class Widget(QWidget):
def __init__(self):
super().__init__()
lay = QVBoxLayout()
self.btn = QPushButton('change layout')
self.btn.clicked.connect(self.btnClick)
self.subWidget = SubWidget()
lay.addWidget(self.btn)
lay.addWidget(self.subWidget)
self.setLayout(lay)
def btnClick(self, check=False):
self.subWidget.change()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()
The code output GUI is:
And I hope it change to the following picture after click change layout button:
Any suggestion is appreciated~~~
The point of the solution is
Make sure old layout is deleted, included both python wrapping reference and core Qt object, that's for deleteLater() is used.
Make sure new layout is assigned strictly after old was deleted, that's for need to use destroyed()-switchlayout() signal-slot chain.
I reproduced example with PySide6 (don't forget to switch on your version of PyQt or PySide package):
# from PyQt5.QtWidgets import *
from PySide6.QtWidgets import *
import sys
class SubWidget(QWidget):
def __init__(self):
super().__init__()
self.lay = QVBoxLayout()
self.label1 = QLabel('left')
self.label2 = QLabel('right')
self.lay.addWidget(self.label1)
self.lay.addWidget(self.label2)
self.setLayout(self.lay)
def change(self):
self.lay.removeWidget(self.label1)
self.lay.removeWidget(self.label2)
self.lay.deleteLater()
self.lay.destroyed.connect(self.switchlayout)
def switchlayout(self):
# print("***destroyed")
self.lay = QHBoxLayout()
self.lay.addWidget(self.label2)
self.lay.addWidget(self.label1)
self.setLayout(self.lay)
self.adjustSize()
class Widget(QWidget):
def __init__(self):
super().__init__()
lay = QVBoxLayout()
self.btn = QPushButton('change layout')
self.btn.clicked.connect(self.btnClick)
self.subWidget = SubWidget()
lay.addWidget(self.btn)
lay.addWidget(self.subWidget)
self.setLayout(lay)
def btnClick(self, check=False):
self.subWidget.change()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()

How can I resize the window after a widget is hidden while still allowing the window to be resized?

Here is a simple example:
from PyQt4 import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
super(MainWindow, self).__init__()
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def startup(self):
self.show()
sys.exit(self.app.exec_())
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
if __name__ == "__main__":
myApp = MainWindow()
myApp.startup()
When the button is toggled, the frame is shown/hidden appropriately. I realize if I set the MainWindows sizeConstraint to SetFixedSize as follows:
layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
that the window will resize like I want. However, I wish for the user to still be able to resize the window, which SetFixedSize will not allow me to do.
Therefore, how can I achieve both a user-resizeable window while still having it resize based on it's contents?
Based on the conversation found here I was able to get this to work. The solution involved adding a QTimer after showing/hiding the frame. The QTimer calls a resizeMe method, which is also defined below.
from PyQt4 import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
super(MainWindow, self).__init__()
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
self.layout = layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def startup(self):
self.show()
sys.exit(self.app.exec_())
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.resizeMe)
def resizeMe(self):
self.resize(self.minimumSizeHint())
if __name__ == "__main__":
myApp = MainWindow()
myApp.startup()

python3.4 + pyqt5: Getting x,y out of QMouseEvent

python3.4+pyqt5
I'm trying to write a program in which buttons shall create other buttons by dragging and press_releasing to form a representation of a rolling mill street.
I created a class Button which does the moving and handles several clicking events for the buttons in creation. This part is working fine.
Where I'm stuck is, I want to read the mouse position where these button should be created.
Here's the code:
def createConnects(self):
self.id000001.released.connect(self.do_something)
self.id000002.released.connect(self.do_something)
#QtCore.pyqtSlot()
def do_something(self):
self.bname = 'Button'
self.button = Button(self.bname, self)
posx = QtGui.QMouseEvent.x()
print(posx)
posy = QtGui.QMouseEvent.y
print(posy)
sender = self.sender()
print(str(sender.objectName()))
#self.button.move(posx, posy)
qmouseevent provides several functions, but the posx line gives me this error:
TypeError: QMouseEvent.x(): first argument of unbound method must have type 'QMouseEvent'
posy-line gives < built-in function y > which isn't what I want, too, but clear.
MouseTracking is switched on in MainWindow class.
Maybe, normaly one would do that by using event in the def line but since it's a slot, that would lead to other problems.
Any hints to get along?
Update:
As recommended here's the full code of the prototype:
#!/usr/bin/env python3.4
import sys, os, math, shutil, re
from subprocess import call, Popen
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.uic import loadUiType
Ui_MainWindow, QMainWindow = loadUiType('mainwindow.ui')
def main(argv):
app = QtWidgets.QApplication(argv)
mainwindow = MyMainWindow()
mainwindow.show()
sys.exit(app.exec_())
class Button(QtWidgets.QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
self.button = QtWidgets.QPushButton()
def mouseMoveEvent(self, event):
if event.buttons() != QtCore.Qt.RightButton:
return
mimeData = QtCore.QMimeData()
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(event.pos() - self.rect().topLeft())
dropAction = drag.exec_(QtCore.Qt.MoveAction)
def mousePressEvent(self, event):
QtWidgets.QPushButton.mousePressEvent(self, event)
if event.button() == QtCore.Qt.LeftButton:
print(event.button(),' pressed')
class MyMainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self, *args):
QtWidgets.QMainWindow.__init__(self, *args)
self.setupUi(self)
self.setMouseTracking(True)
self.createConnects()
def dragEnterEvent(self, event):
event.accept()
def dropEvent(self, event):
position = event.pos()
self.button.move(position)
event.setDropAction(QtCore.Qt.MoveAction)
event.accept()
def createConnects(self):
self.id000001.released.connect(self.do_something)
self.id000002.released.connect(self.do_something)
#QtCore.pyqtSlot()
def do_something(self):
print('do_something')
self.bname = 'Button'
self.button = QtWidgets.QPushButton()
#self.button = Button(self.bname, self)
self.button.move(100, 65)
#posx = QtGui.QMouseEvent.x()
#print(posx)
#posy = QtGui.QMouseEvent.y
#print(posy)
sender = self.sender()
print(str(sender.objectName()))
#self.button.move(posx, posy)
if __name__ == '__main__':
main(sys.argv)
cheers,
Christian

PyQt-QtableView Header. How to add top-right small button to hide/show column with checked/unchecked Checkboxes?

With PyQt4, I am using a QtableView with more than 10 columns. The user must have the choice of showing/hiding a column.
This is generally done by adding a small button in the top-right of the table's header. The button shows a menu with checked/unchecked Checkboxes allowing to hide/show columns.
This is an example from Sqlite-Manager Table.
So, I wonder how can I do the same with PyQt's QtableView?
Thanks,
Thank you Kitsune Meyoko, it was a great Idea.. ;)
I found another solution pretty much like yours by using QMenu with Checkable QActions instead of a QPushButton: Let's Go:
import sys
import string
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Header(QHeaderView):
def __init__(self, parent=None):
super(Header, self).__init__(Qt.Horizontal, parent)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.ctxMenu)
self.setup()
#pyqtSlot(bool)
def printID(self, i):
print("id")
if i == False:
self.hideSection(0)
else:
self.showSection(0)
#pyqtSlot(bool)
def printNAME(self, i):
print("name")
if i == False:
self.hideSection(1)
else:
self.showSection(1)
#pyqtSlot(bool)
def printUSERNAME(self, i):
print("username")
if i == False:
self.hideSection(2)
else:
self.showSection(2)
def setup(self):
self.id = QAction("id",self)
self.id.setCheckable(True)
self.id.setChecked(True)
self.connect(self.id, SIGNAL("triggered(bool)"), self, SLOT("printID(bool)"))
self.name = QAction("name",self)
self.name.setCheckable(True)
self.name.setChecked(True)
self.connect(self.name, SIGNAL("triggered(bool)"), self, SLOT("printNAME(bool)"))
self.username = QAction("username",self)
self.username.setCheckable(True)
self.username.setChecked(True)
self.connect(self.username, SIGNAL("triggered(bool)"), self, SLOT("printUSERNAME(bool)"))
def ctxMenu(self, point):
menu = QMenu(self)
self.currentSection = self.logicalIndexAt(point)
menu.addAction(self.id)
menu.addAction(self.name)
menu.addAction(self.username)
menu.exec_(self.mapToGlobal(point))
class Table(QTableWidget):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
self.setHorizontalHeader(Header(self))
self.setColumnCount(3)
self.setHorizontalHeaderLabels(['id', 'name', 'username'])
self.populate()
def populate(self):
self.setRowCount(10)
for i in range(10):
for j,l in enumerate(string.ascii_letters[:3]):
self.setItem(i, j, QTableWidgetItem(l))
if __name__ == '__main__':
app = QApplication(sys.argv)
t = Table()
t.show()
app.exec_()
sys.exit()
In QTableView not have kind of button just like "Sqlite-Manager Table". But your can custom widget by using QtGui.QPushButton and work with QtGui.QMenu together to get column from user. And use QTableView.hideColumn (self, int column) & QTableView.showColumn (self, int column) to hide show your column;
Full example;
import sys
import random
from functools import partial
from PyQt4 import QtGui
class QCustomTableViewWidget (QtGui.QWidget):
def __init__ (self, myQStandardItemModel, *args, **kwargs):
super(QCustomTableViewWidget, self).__init__(*args, **kwargs)
# Layout setup
self.localQTableView = QtGui.QTableView()
self.rightCornerQPushButton = QtGui.QPushButton()
menuQHBoxLayout = QtGui.QHBoxLayout()
menuQHBoxLayout.addStretch(1)
menuQHBoxLayout.addWidget(self.rightCornerQPushButton)
allQVBoxLayout = QtGui.QVBoxLayout()
allQVBoxLayout.addLayout(menuQHBoxLayout)
allQVBoxLayout.addWidget(self.localQTableView)
self.setLayout(allQVBoxLayout)
# Object setup
self.localQTableView.setModel(myQStandardItemModel)
self.rightCornerQPushButton.setText('Show column')
currentQMenu = QtGui.QMenu()
for column in range(myQStandardItemModel.columnCount()):
currentQAction = QtGui.QAction('Column %d' % (column + 1), currentQMenu)
currentQAction.setCheckable(True)
currentQAction.setChecked(True)
currentQAction.toggled.connect(partial(self.setColumnVisible, column))
currentQMenu.addAction(currentQAction)
self.rightCornerQPushButton.setMenu(currentQMenu)
def setColumnVisible (self, column, isChecked):
if isChecked:
self.localQTableView.showColumn(column)
else:
self.localQTableView.hideColumn(column)
def tableView (self):
return self.localQTableView
# Simulate data
myQStandardItemModel = QtGui.QStandardItemModel()
for _ in range(10):
myQStandardItemModel.appendRow([QtGui.QStandardItem('%d' % random.randint(100, 999)), QtGui.QStandardItem('%d' % random.randint(100, 999)), QtGui.QStandardItem('%d' % random.randint(100, 999))])
# Main application
myQApplication = QtGui.QApplication(sys.argv)
myQCustomTableViewWidget = QCustomTableViewWidget(myQStandardItemModel)
myQCustomTableViewWidget.show()
sys.exit(myQApplication.exec_())

Disable sorting of child items in QTreeView

I am using pyQt. How can I disable child items sorting in QTreeView/StandardItemModel?
You could use a QSortFilterProxyModel and reimplement its lessThan method.
Alternatively, create a subclass of QStandardItem and reimplement its less than operator.
Here's a simple example that demonstrates the latter approach:
from random import sample
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.view = QtGui.QTreeView(self)
self.view.setHeaderHidden(True)
self.model = QtGui.QStandardItemModel(self.view)
self.view.setModel(self.model)
parent = self.model.invisibleRootItem()
keys = range(65, 91)
for key in sample(keys, 10):
item = StandardItem('Item %s' % chr(key), False)
parent.appendRow(item)
for key in sample(keys, 10):
item.appendRow(StandardItem('Child %s' % chr(key)))
self.view.sortByColumn(0, QtCore.Qt.AscendingOrder)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.view)
class StandardItem(QtGui.QStandardItem):
def __init__(self, text, sortable=True):
QtGui.QStandardItem.__init__(self, text)
self.sortable = sortable
def __lt__(self, other):
if getattr(self.parent(), 'sortable', True):
return QtGui.QStandardItem.__lt__(self, other)
return False
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Call setSortingEnabled(bool) on your QTreeView instance. Here is the corresponding docu for c++ and here is the link to pyqt api docu for this function

Resources