I'm having trouble with a program that I'm writing. As its going to be quite large, I want to separate the layouts and signals, etc into separate classes/modules to make things easier to read. I would like to be able to edit the layout widgets from another class. Is this possible, or am I trying to do something that is not possible? I've included an example below, in case my explanation is not clear
class Layout:
def __init__(self):
self.callback = CallBack()
def Gui(self):
'''
some layout with a listwidget that affects another listwidget depending on choice for example
'''
self.list1 = QtGui.QListWidget()
self.list1.addItems(['chocolate', 'candy', 'pop'])
self.list1.itemClicked.connect(self.callback.ButtonCallback)
self.list2 = QtGui.QListWidget()
class CallBack(Layout):
def __init__(self)
super(CallBack, self).__init__()
def ButtonCallback(self, button_signal):
'''
do get options for self.list2 depending on chosen item
'''
new_items = ['item1', 'item2', 'item3']
Layout.list2.addItems(new_items)
I realize that the last line of the code is probably wrong but that is the part that I'm struggling with.
Many thanks for any help.
You can certainly have other objects answer your signals for you as long as they conform to QObject. In the example code that you have written, I would create the CallBack object as a subclass of QObject and retain a relationship to the Layout that owns it so that it can access the Layout object's attributes.
class Layout:
def __init__(self):
self.callback = CallBack(self)
def Gui(self):
'''
some layout with a listwidget that affects another listwidget depending on choice for example
'''
self.list1 = QtGui.QListWidget()
self.list1.addItems(['chocolate', 'candy', 'pop'])
self.list1.itemClicked.connect(self.callback.ButtonCallback)
self.list2 = QtGui.QListWidget()
class CallBack(QtCore.QObject):
def __init__(self, parent)
super(CallBack, self).__init__()
self.parent = parent
def ButtonCallback(self, button_signal):
'''
do get options for self.parent.list2 depending on chosen item
'''
new_items = ['item1', 'item2', 'item3']
self.parent.list2.addItems(new_items)
Related
I am making a program for translating text (see screenshot)
I have three classes
class for displaying a window that edits item :
class StyleDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(StyleDelegate, self).__init__()
def createEditor(self, widget, style, index):
self.mainWidget = QWidget(widget)
self.line = QLineEdit() # line for input text
self.delButton= QPushButton('❌') # button for delete current item
self.trnButton = QPushButton('➕') # button for make translation text in another QListView
self.qhbLayout = QHBoxLayout()
self.qhbLayout.addWidget(self.line)
self.qhbLayout.addWidget(self.delButton)
self.qhbLayout.addWidget(self.trnButton)
self.mainWidget.setLayout(self.qhbLayout)
return self.mainWidget
# there is still a lot of code in this place
class for storing, adding, deleting and editing data:
class TranslateListModel(QAbstractListModel):
def __init__(self, parent=None):
super(TranslateListModel, self).__init__()
self.words = ['1', '2', '3', '4']
def removeItem(self, index):
self.beginRemoveRows(index, index.row(), index.row())
del self.words[index.row()]
self.endRemoveRows()
return True
# there is still a lot of code in this place
main class of the program:
class QTranslate(QtWidgets.QDialog, log.Ui_Dialog):
def __init__(self):
super().__init__()
self.originalModel = TranslateListModel()
self.translateModel = TranslateListModel()
self.styleDelegate = StyleDelegate()
self.originalLV.setModel(self.originalModel)
#QListView from Ui_Dialog
self.translateLV.setModel(self.translateModel)
#QListView from Ui_Dialog
self.originalLV.setItemDelegate(self.styleDelegate)
self.translateLV.setItemDelegate(self.styleDelegate)
# there is still a lot of code in this place
How to implement buttons to delete the current item and change the translation in another QListView using QStyledItemDelegate? I cannot access these buttons outside the StyleDelegate class to associate them with the methods of the TranslateListModel class.
A possible solution is to create signals for the delegate and connect them to the functions that will delete or add items, then emit those signals when the buttons are clicked:
class StyleDelegate(QStyledItemDelegate):
deleteRequested = QtCore.pyqtSignal(int)
translateRequested = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(StyleDelegate, self).__init__()
def createEditor(self, widget, style, index):
# note: I removed the "self" references as they're unnecessary
mainWidget = QWidget(widget)
line = QLineEdit()
delButton= QPushButton('❌')
trnButton = QPushButton('➕')
qhbLayout = QHBoxLayout()
qhbLayout.addWidget(line)
qhbLayout.addWidget(delButton)
qhbLayout.addWidget(trnButton)
mainWidget.setLayout(qhbLayout)
delButton.clicked.connect(
lambda _, row=index.row(): self.deleteRequested.emit(row))
trnButton.clicked.connect(
lambda _, row=index.row(): self.translateRequested.emit(row))
return mainWidget
class QTranslate(QtWidgets.QDialog, log.Ui_Dialog):
def __init__(self):
# ...
self.originalLV.setItemDelegate(self.styleDelegate)
self.styleDelegate.deleteRequested.connect(self.deleteRow)
self.styleDelegate.translateRequested.connect(self.translateRow)
def deleteRow(self, row):
# ...
def translateRow(self, row):
# ...
Note that you should always use an unique delegate instance for each view, as explained in the documentation:
Warning: You should not share the same instance of a delegate between views. Doing so can cause incorrect or unintuitive editing behavior since each view connected to a given delegate may receive the closeEditor() signal, and attempt to access, modify or close an editor that has already been closed.
I'm trying to figure out how I can get the QWidget that I insert into a QListWidget as a QListWidgetItem to be able to access the list it is a part of so that it can do the following:
Increase/decrease it's position in the list
Remove itself from the list
Pass information from it's own class to a function in the main class
My script layout is a main.py which is where the MainWindow class is. The MainWindow uses the class generated from the main ui file. I also have the custom widget which is it's own class.
Example of GUI:
Relevant code snippets:
main.py
from PyQt4.QtGui import QMainWindow, QApplication
from dungeonjournal import Ui_MainWindow
from creature_initiative_object import InitCreatureObject
from os import walk
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(QMainWindow, self).__init__(parent)
self.setupUi(self)
etc......
def AddToInitiative(self):
creature = self.comboBoxSelectCharacter.currentText()
if(creature):
creatureInfo = ''
with open("creatures/"+str(creature)+".creature", "r") as f:
creatureInfo = f.read()
creatureInfo = creatureInfo.split("|")
customWidget = InitCreatureObject()
customWidgetItem = QtGui.QListWidgetItem(self.initiativeList)
customWidgetItem.setSizeHint(QtCore.QSize(400,50))
self.initiativeList.addItem(customWidgetItem)
self.initiativeList.setItemWidget(customWidgetItem, customWidget)
customWidget.setName(creatureInfo[0])
return
creature_initiative_object.py
class Ui_InitCreatureObject(object):
def setupUi(self, InitCreatureObject):
etc...
class InitCreatureObject(QtGui.QWidget, Ui_InitCreatureObject):
def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QWidget.__init__(self, parent, f)
self.setupUi(self)
Edit 1:
To clarify again, I need to be able to use the buttons in the widget to modify the position of itself in the list. The list is part of the main ui. The buttons for up arrow, down arrow, Select, and Remove are the one's I'm trying to get to interact with things outside of their class.
The function they call needs to be able to determine which listItem is being called, be able to modify the list.
For example, if I click remove, it then needs to know which item in the list to remove. So it needs to first know what the list is, then it needs to know what item it is. I'm not sure how to access the instance of the widget that is occupying that listitem. I also am not sure how to get that listitem based on a button press from inside that listitem's class.
Edit 2:
Per the first answer I tried to work that into my code.
main.py had the following function added
def RemoveItem(self):
cwidget = self.sender().parent()
item = self.initiativeList.itemAt(cwidget.pos())
row = self.initiativeList.row(item)
self.initiativeList.takeItem(row)
print(row)
creature_initiative_object.py had the following added to the InitCreatureObject class
class InitCreatureObject(QtGui.QWidget, Ui_InitCreatureObject):
def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QWidget.__init__(self, parent, f)
self.setupUi(self)
self.mainwidget = main.MainWindow()
self.btnRemove.clicked.connect(self.mainwidget.RemoveItem)
Item is still not being passed. The parent object seems to be right but when I get the row it always says -1.
The strategy to get the QTableWidgetItem is to use the itemAt() method but for this you must know the position of some point within the QTableWidgetItem.
Since the main objective is to get the item when a signal is sent, then the connected slot is used, so I recommend connecting all the signals to that slot. Given the above the following steps are taken:
Get the object that emits the signal through sender().
Get the sender parent() since this will be the custom widget that was added to the QListWidget() along with the item.
Get the position of the custom widget through pos(), this is the position that should be used in the itemAt() method.
Then you get the text of the button or some parameter that tells me the task to know what action you want to do.
The above can be implemented as follows:
def someSlot(self):
p = self.sender().parent()
it = self.lw.itemAt(p.pos())
text = self.sender().text()
if text == "task1":
do task1
elif text == "task2":
do task2
From the above, the following example is proposed:
class CustomWidget(QWidget):
def __init__(self, text, parent=None):
QWidget.__init__(self, parent)
self.setLayout(QHBoxLayout())
self.buttons = []
vb = QVBoxLayout()
self.layout().addLayout(vb)
self.btnTask1 = QPushButton("task1")
self.btnTask2 = QPushButton("task2")
vb.addWidget(self.btnTask1)
vb.addWidget(self.btnTask2)
self.buttons.append(self.btnTask1)
self.buttons.append(self.btnTask2)
self.btnTask3 = QPushButton("task3")
self.btnTask4 = QPushButton("task4")
self.btnTask5 = QPushButton("task5")
self.btnTask6 = QPushButton("task6")
self.layout().addWidget(self.btnTask3)
self.layout().addWidget(self.btnTask4)
self.layout().addWidget(self.btnTask5)
self.layout().addWidget(self.btnTask6)
self.buttons.append(self.btnTask3)
self.buttons.append(self.btnTask4)
self.buttons.append(self.btnTask5)
self.buttons.append(self.btnTask6)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.lw = QListWidget(self)
self.setCentralWidget(self.lw)
for i in range(5):
cw = CustomWidget("{}".format(i))
for btn in cw.buttons:
btn.clicked.connect(self.onClicked)
item = QListWidgetItem(self.lw)
item.setSizeHint(QSize(400, 80))
self.lw.addItem(item)
self.lw.setItemWidget(item, cw)
def onClicked(self):
p = self.sender().parent()
it = self.lw.itemAt(p.pos())
row = self.lw.row(it)
text = self.sender().text()
print("item {}, row {}, btn: {}".format(it, row, text))
#if text == "task1":
# do task1
#elif text == "task2":
# do task2
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
In your Case:
class MainWindow(QMainWindow, Ui_MainWindow):
[...]
def AddToInitiative(self):
[...]
customWidget = InitCreatureObject()
customWidget.btnRemove.clicked.connect(self.RemoveItem)
# ^^^^^
[...]
def RemoveItem(self):
cwidget = self.sender().parent()
item = self.initiativeList.itemAt(cwidget.pos())
row = self.initiativeList.row(item)
self.initiativeList.takeItem(row)
print(row)
This question is similar to the one in this this topic Preserve QStandardItem subclasses in drag and drop but with issue that I cant find a good solution for. That topic partially helps but fail on more complex task.
When I create an item in QTreeView I put that item in my array but when I use drag&Drop the item gets deleted and I no longer have access to it. I know that its because drag and drop copies the item and not moves it so I should use setData. I cant setData to be an object because even then the object gets copied and I lose reference to it.
Here is an example
itemsArray = self.addNewRow
def addNewRow(self)
'''some code with more items'''
itemHolder = QStandardItem("ProgressBarItem")
widget = QProgressBar()
itemHolder.setData(widget)
inx = self.model.rowCount()
self.model.setItem(inx, 0, itemIcon)
self.model.setItem(inx, 1, itemName)
self.model.setItem(inx, 2, itemHolder)
ix = self.model.index(inx,2,QModelIndex())
self.treeView.setIndexWidget(ix, widget)
return [itemHolder, itemA, itemB, itemC]
#Simplified functionality
data = [xxx,xxx,xxx]
for items in itemsArray:
items[0].data().setPercentage(data[0])
items[1].data().setText(data[1])
items[2].data().setChecked(data[2])
The code above works if I won't move the widget. The second I drag/drop I lose reference I lose updates on all my items and I get crash.
RuntimeError: wrapped C/C++ object of type QProgressBar has been deleted
The way I can think of of fixing this problem is to loop over entire treeview recursively over each row/child and on name match update item.... Problem is that I will be refreshing treeview every 0.5 second and have 500+ rows with 5-15 items each. Meaning... I don't think that will be very fast/efficient... if I want to loop over 5 000 items every 0.5 second...
Can some one suggest how I could solve this problem? Perhaps I can edit dropEvent so it does not copy/paste item but rather move item.... This way I would not lose my object in array
Qt can only serialize objects that can be stored in a QVariant, so it's no surprise that this won't work with a QWidget. But even if it could serialize widgets, I still don't think it would work, because index-widgets belong to the view, not the model.
Anyway, I think you will have to keep references to the widgets separately, and only store a simple key in the model items. Then once the items are dropped, you can retrieve the widgets and reset them in the view.
Here's a working demo script:
from PyQt4 import QtCore, QtGui
class TreeView(QtGui.QTreeView):
def __init__(self, *args, **kwargs):
super(TreeView, self).__init__(*args, **kwargs)
self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAllColumnsShowFocus(True)
self.setModel(QtGui.QStandardItemModel(self))
self._widgets = {}
self._dropping = False
self._droprange = range(0)
def dropEvent(self, event):
self._dropping = True
super(TreeView, self).dropEvent(event)
for row in self._droprange:
item = self.model().item(row, 2)
self.setIndexWidget(item.index(), self._widgets[item.data()])
self._droprange = range(0)
self._dropping = False
def rowsInserted(self, parent, start, end):
super(TreeView, self).rowsInserted(parent, start, end)
if self._dropping:
self._droprange = range(start, end + 1)
def addNewRow(self, name):
model = self.model()
itemIcon = QtGui.QStandardItem()
pixmap = QtGui.QPixmap(16, 16)
pixmap.fill(QtGui.QColor(name))
itemIcon.setIcon(QtGui.QIcon(pixmap))
itemName = QtGui.QStandardItem(name.title())
itemHolder = QtGui.QStandardItem('ProgressBarItem')
widget = QtGui.QProgressBar()
widget.setValue(5 * (model.rowCount() + 1))
key = id(widget)
self._widgets[key] = widget
itemHolder.setData(key)
model.appendRow([itemIcon, itemName, itemHolder])
self.setIndexWidget(model.indexFromItem(itemHolder), widget)
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.treeView = TreeView()
for name in 'red yellow green purple blue orange'.split():
self.treeView.addNewRow(name)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.treeView)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 150, 600, 400)
window.show()
sys.exit(app.exec_())
I have two classes here and I want the label from the parent class to be available in the child class. I've tried making the label a global variable but that doesn't seem to work either unless I'm doing something wrong (I've only been using Python for two weeks). Here's the code.
from tkinter import *
class Parent_Class(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_labels()
def create_labels(self):
self.label_1 = Label(self)
self.label_1["text"] = "I'm in the Parent Class."
self.label_1.grid(row = 0, column = 0, sticky = W)
class Child_Class():
def __init__(self):
self.change_label()
def change_label(self):
label_1["text"] = "I'm in the Child Class."
window = Tk()
window.title("Label Test")
window.geometry("250x250")
app = Parent_Class(window)
window.mainloop()
You should never directly change a widget outside of a class that creates it. If you choose to modify that original class, you end up having to change two or more classes. Instead, you give the class with the label an interface that other classes can use. You can directly access the label, but it results in what is called "tight coupling"
Regardless, the key to making it work is that you have to pass to the child a reference to the parent.
It works something like this, using an interface. Again, you could directly access parent.label instead of calling an interface, but that's generally a bad idea.
class Parent_Class(...):
def __init__(self, ...):
...
self.label = Label(...)
...
def set_label(self, string):
self.label.configure(text=string)
class Child_Class(...):
def __init__(self, parent):
...
self.parent = parent
...
def change_label(self):
self.parent.set_label("I'm in the Child Class")
# of, if tight coupling is acceptable to you:
# self.parent.label.configure(text="I'm in the Child Class")
...
p = Parent_Class(...)
c = Child_Class(parent=p)
I have a code which consists of 3 classes. The classes widget1 and widget2 inherit from QFrame class and consists of several lineedit and combobox for the user to enter information.
So, what I want is: when the program is launched, it will firstly bring up the QMainWindow class with widget1 set as the central widget.
The widget1 has a Check function which is connected to a button on it. The check button will check whether a condition is true based on the data entered by the user on the page.
If the condition is true. I want the widget2 to set it as central wiget of MainWindow to replace existing central widget, the widget1.
My question is, how do I set the widget2 as the central widget of existing MainWidnow class instance?
This is the format of my code:
class widget1(QtGui.QFrame):
def __init__(self,parent = None):
......
......
def Check(self):
if (condition):
#set widget2 as central widget on MainWindow
class widget2(QtGui.QFrame):
def __int__(self,parent = None):
.....
.....
class MainWindow(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
....
mywidgetone = widget1()
self.setCentralWidget(mywidgetone)
if __name__ == '__main__':
app = QtGui.QApplicaiton(sys.argv)
main = MainWindow()
main.show()
app.exec_()
I'd do the following for MainWindow:
class MainWindow(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
....
self.setMyCentral(widget1)
def setMyCentral(self, widgetClass):
mywidget = widgetClass(self)
self.setCentralWidget(mywidget)
and then, in widget1:
def Check(self):
if (condition):
self.parent().setMyCentral(widget2)
Now, please, follow the conventions: classes start in capital letters (Widget1, Widget2) and methods don't (check instead of Check)
Another option is a panel creates all 3 widgets but set widget2 and 3 visible = false. Then when time to change, set widget1 visible=false, and widget2 visible. Etc. You set the panel as central widget, this never changes. Just the panel decides which one of its three children to show.