Qcombobox with Qlabel and signal&slot - python

I have a Qgroupbox which contains Qcombobox with Qlabels, I want to select a value from Qcombobox and display the value as Qlabel. I have the complete code, even I do print value before and after within function every thing works as it should, Only display setText wont set text to Qlabel and update it.
Current screen
What I want
I've corrected signal code, when Qgroupbox in it Qcombobox appears or value would be changed, self.activation.connect(......) would emit an int of the index. to ensure that would work I print it-value inside the def setdatastrength(self, index), see figure below indeed it works, then argument would be passed to function self.concreteproperty.display_condata(it) would be called and do a print of value inside def display_condata(self, value) to make sure about value passing, as shown figure below, it does work. This line code self.con_strength_value.setText(fmt.format(L_Display))
wont assign value to Qlabel.
The script
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class secondtabmaterial(QtWidgets.QWidget):
def __init__(self, parent=None):
super(secondtabmaterial, self).__init__(parent)
self.concretewidgetinfo = ConcreteStrengthInFo()
Concrete_Group = QtWidgets.QGroupBox(self)
Concrete_Group.setTitle("&Concrete")
Concrete_Group.setLayout(self.concretewidgetinfo.grid)
class ConcreteStrengthComboBox(QtWidgets.QComboBox):
def __init__(self, parent = None):
super(ConcreteStrengthComboBox, self).__init__(parent)
self.addItems(["C12/15","C16/20","C20/25","C25/30","C30/37","C35/45"
,"C40/50","C45/55","C50/60","C55/67","C60/75","C70/85",
"C80/95","C90/105"])
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.compressive_strength = ["12","16","20","25","30","35","40",
"45","50","55","60","70","80","90"]
class ConcreteProperty(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteProperty, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
concretestrength_lay = QtWidgets.QHBoxLayout(self)
fctd = "\nfcd\n\nfctd\n\nEc"
con_strength = QtWidgets.QLabel(fctd)
self.con_strength_value = QtWidgets.QLabel(" ")
concretestrength_lay.addWidget(con_strength)
concretestrength_lay.addWidget(self.con_strength_value, alignment=QtCore.Qt.AlignRight)
self.setLayout(concretestrength_lay)
#QtCore.pyqtSlot(int)
def display_condata(self, value):
try:
L_Display = str(value)
print("-------- After ------")
print(L_Display, type(L_Display))
fmt = "{}mm"
self.con_strength_value.setText(fmt.format(L_Display))
except ValueError:
print("Error")
class ConcreteStrengthInFo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteStrengthInFo, self).__init__(parent)
self.concreteproperty = ConcreteProperty()
self.concretestrengthbox = ConcreteStrengthComboBox()
self.concretestrengthbox.activated.connect(self.setdatastrength)
hbox = QtWidgets.QHBoxLayout()
concrete_strength = QtWidgets.QLabel("Concrete strength: ")
hbox.addWidget(concrete_strength)
hbox.addWidget(self.concretestrengthbox)
self.grid = QtWidgets.QGridLayout()
self.grid.addLayout(hbox, 0, 0)
self.grid.addWidget(self.concreteproperty, 1, 0)
#QtCore.pyqtSlot(int)
def setdatastrength(self, index):
it = self.concretestrengthbox.compressive_strength[index]
self.concreteproperty.display_condata(it)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = secondtabmaterial()
w.show()
sys.exit(app.exec_())
Above code is corrected and final. Now it works as it should.

I think the issue is that your receiving slot doesn't match any of the available .activated signals.
self.activated.connect(self.setdatastrength)
#QtCore.pyqtSlot()
def setdatastrength(self):
index = self.currentIndex()
it = self.compressive_strength[index]
print(it)
self.concreteproperty.display_condata(it)
The QComboBox.activated signal emits either an int of the index, or a str of the selected value. See documentation.
You've attached it to setdatastrength which accepts doesn't accept any parameters (aside from self, from the object) — this means it doesn't match the signature of either available signal, and won't be called. If you update the definition to add the index value, and accept a single int it should work.
self.activated.connect(self.setdatastrength)
#QtCore.pyqtSlot(int) # add the target type for this slot.
def setdatastrength(self, index):
it = self.compressive_strength[index]
print(it)
self.concreteproperty.display_condata(it)
After the update — the above looks now to be fixed, although you don't need the additional index = self.currentIndex() in setdatastrength it's not doing any harm.
Looking at your code, I think the label is being updated. The issue actually is that you can't see the label at all. Looking at the init for ConcreteProperty
class ConcreteProperty(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteProperty, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.concretestrength_lay = QtWidgets.QHBoxLayout()
fctd = "\nfcd\n\nfctd\n\nEc"
con_strength = QtWidgets.QLabel(fctd)
self.con_strength_value = QtWidgets.QLabel(" ")
self.concretestrength_lay.addWidget(con_strength)
self.concretestrength_lay.addWidget(self.con_strength_value, alignment=QtCore.Qt.AlignLeft)
The reason the changes are not appearing is that you create two ConcreteProperty objects, one in ConcreteStrengthInfo and one in ConcreteStrengthComboBox. Updates to the combo box trigger an update of the ConcreteProperty attached to the combobox, not the other one (they are separate objects). The visible ConcreteProperty is unaffected.
To make this work, you need to move the signal attachment + the slot out of the combo box object. The following is a replacement for the two parts —
class ConcreteStrengthComboBox(QtWidgets.QComboBox):
def __init__(self, parent = None):
super(ConcreteStrengthComboBox, self).__init__(parent)
self.addItems(["C12/15","C16/20","C20/25","C25/30","C30/37","C35/45","C40/50","C45/55",
"C50/60","C55/67","C60/75","C70/85","C80/95","C90/105"])
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.compressive_strength = ["12","16","20","25","30","35","40","45","50","55",
"60","70","80","90"]
class ConcreteStrengthInFo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteStrengthInFo, self).__init__(parent)
hbox = QtWidgets.QHBoxLayout()
concrete_strength = QtWidgets.QLabel("Concrete strength: ")
hbox.addWidget(concrete_strength)
self.concreteproperty = ConcreteProperty()
self.concretestrengthbox = ConcreteStrengthComboBox()
hbox.addWidget(self.concretestrengthbox)
self.concretestrengthbox.activated.connect(self.setdatastrength)
self.vlay = QtWidgets.QVBoxLayout()
self.vlay.addLayout(hbox)
self.vlay.addLayout(self.concreteproperty.concretestrength_lay)
#QtCore.pyqtSlot(int)
def setdatastrength(self, index):
it = self.concretestrengthbox.compressive_strength[index]
print(it)
self.concreteproperty.display_condata(it)
This works for me locally.

Related

Using QStyledItemDelegates as custom items in QListView

I want to design a custom ListView widget which has custom items similar to this:
https://i.stack.imgur.com/iTNbN.png
However, the qt documentation and some stackoverflow posts state that one should ideally use a QStyleItemDelegate. I never worked with 'delegates' before but as far as I understood from my research they are called by the ListView for drawing / rendering each item.
I found a delegate example in another project (https://github.com/pyblish/pyblish-lite/blob/master/pyblish_lite/delegate.py) and they draw everything by hand / are essentially rebuilding entire widgets by painting rectangles.
This seems a bit impractical for me as most of the time custom item widgets can be compounds of existing widgets. Take a look at the screenshot above. It essentially contains a Qlabel, QPixmap, and four DoubleSpinBoxes.
Question: How would you use the painting / rendering methods that already exist in them instead of manually painting everything on your own?
That way you can profit from existing member methods and can use layouts for structuring your widget.
For example the first ListViewItem should pass the model data to the delegate so that the text of the self.lightGroupName QLabel can be set to "Light1".
Any help is greatly appreciated, since I have no idea how to go on from here:
from PySide2 import QtCore, QtGui, QtWidgets
class LightDelagate(QtWidgets.QStyledItemDelegate): #custom item view
def __init__(self, parent=None):
super(LightDelagate, self).__init__(parent)
self.setupUI()
def setupUI(self):
self.masterWidget = QtWidgets.QWidget()
#Light Group Header
self.hlayLightHeader = QtWidgets.QHBoxLayout()
self.lightGroupName = QtWidgets.QLabel("Checker")
self.hlayLightHeader.addWidget(self.lightGroupName)
#Light AOV Preview
self.lightPreview = QtWidgets.QLabel()
#set size
self.aovThumbnail = QtGui.QPixmap(180, 101)
#self.lightPreview.setPixmap(self.aovThumbnail.scaled(self.lightPreview.width(), self.lightPreview.height(), QtCore.Qt.KeepAspectRatio))
# #Color Dials
# self.hlayColorDials = QtWidgets.QHBoxLayout()
# self.rgbDials = QtWidgets.QHBoxLayout()
# self.rDial = QtWidgets.QDoubleSpinBox()
# self.rDial.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
# self.gDial = QtWidgets.QDoubleSpinBox()
# self.gDial.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
# self.bDial = QtWidgets.QDoubleSpinBox()
# self.bDial.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
# self.rgbDials.addWidget(self.rDial)
# self.rgbDials.addWidget(self.gDial)
# self.rgbDials.addWidget(self.bDial)
# #Exposure
# self.hlayExposureDials = QtWidgets.QHBoxLayout()
# self.exposureDial = QtWidgets.QDoubleSpinBox()
# self.exposureDial.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
# self.hlayExposureDials.addWidget(self.exposureDial)
# self.hlayColorDials.addLayout(self.rgbDials)
# self.hlayColorDials.addLayout(self.hlayExposureDials)
#entire layout
self.vlayWidget = QtWidgets.QVBoxLayout()
self.vlayWidget.addLayout(self.hlayLightHeader)
self.vlayWidget.addWidget(self.lightPreview)
# self.vlayWidget.addLayout(self.hlayColorDials)
self.vlayWidget.setContentsMargins(2,2,2,2)
self.vlayWidget.setSpacing(2)
self.masterWidget.setLayout(self.vlayWidget)
def paint(self, painter, option, index):
rowData = index.model().data(index, QtCore.Qt.DisplayRole)
self.lightGroupName.setText(rowData[0])
print (option.rect)
painter.drawRect(option.rect)
painter.drawText()
def sizeHint(self, option, index):
return QtCore.QSize(200, 150)
class LightListModel(QtCore.QAbstractListModel): #data container for list view
def __init__(self, lightList= None):
super(LightListModel, self).__init__()
self.lightList = lightList or []
#reimplement
def rowCount(self, index):
return len(self.lightList)
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
lightGroupData = self.lightList[index.row()]
return lightGroupData
class LightListView(QtWidgets.QListView): #
def __init__(self):
super(LightListView, self).__init__()
self.setFlow(QtWidgets.QListView.LeftToRight)
self.setItemDelegate(LightDelagate(self))
self.setMinimumWidth(1880)
lightListTest = [
('Light1' , {'lightList' : [], 'lightColor': (0,0,0), 'mod_exposure': 1, 'mod_color' : (0,0,0)}),
('Light2' , {'lightList' : [], 'lightColor': (0,0,0), 'mod_exposure': 1, 'mod_color' : (0,0,0)}),
('Light3' , {'lightList' : [], 'lightColor': (0,0,0), 'mod_exposure': 1, 'mod_color' : (0,0,0)}),
('Light4' , {'lightList' : [], 'lightColor': (0,0,0), 'mod_exposure': 1, 'mod_color' : (0,0,0)})
]
app = QtWidgets.QApplication([])
LLV = LightListView()
model = LightListModel(lightList=lightListTest)
LLV.setModel(model)
LLV.show()
LLV.setSe
app.exec_()
Instead of QListView, could you use QListWidget and override itemWidget? The idea would be that this lets you return a QWidget (with children as per your screenshot) instead of having to implement a QStyledItemDelegate that calls each child widget's paint method.

"QStackedWidget.setCurrentIndex": It does not work or error mark

I'm doing a program with graphical interface using PyQt5 . I want to do is that when the user presses certain button, this change widget and show other options.
For this I decided to use QStackedWidget, and all my interface build it from the QT5 designer.
However, in my code, wanting to determine that my name button "btfr" show me "page_2" of my stackedWidget when pressed, using the QStackedWidget.setCurrentIndex method, this does nothing or make any error.
the code is as follows:
import sys
from PyQt5 import uic
from PyQt5.QtCore import QTimeLine
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
infz = uic.loadUiType("main.ui")[0]
class FaderWidget(QWidget):
def __init__(self, old_widget, new_widget):
QWidget.__init__(self, new_widget)
self.old_pixmap = QPixmap(new_widget.size())
old_widget.render(self.old_pixmap)
self.pixmap_opacity = 1.0
self.timeline = QTimeLine()
self.timeline.valueChanged.connect(self.animate)
self.timeline.finished.connect(self.close)
self.timeline.setDuration(333)
self.timeline.start()
self.resize(new_widget.size())
self.show()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
painter.setOpacity(self.pixmap_opacity)
painter.drawPixmap(0, 0, self.old_pixmap)
painter.end()
def animate(self, value):
self.pixmap_opacity = 1.0 - value
self.repaint()
class StackedWidget(QStackedWidget):
def __init__(self, parent=None):
QStackedWidget.__init__(self, parent)
def setCurrentIndex(self, index):
self.stack = MyWindowClass()
self.a = self.stack.stackedWidget.currentWidget()
self.b = self.stack.stackedWidget.widget(index)
self.fader_widget = FaderWidget(self.a, self.b)
QStackedWidget.setCurrentIndex(self, index)
print(self, index)
def setPage1(self):
self.setCurrentIndex(0)
def setPage2(self):
self.setCurrentIndex(1)
class MyWindowClass(QStackedWidget, infz):
def __init__(self, parent=None):
global pos, c, f
self.pos = 0
self.c = []
self.f = False
QStackedWidget.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle('SkR')
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWindowClass()
window.resize(788, 518)
stack = StackedWidget()
window.btfr.clicked.connect(stack.setPage2)
window.btnpx.clicked.connect(stack.setPage1)
window.show()
sys.exit(app.exec_())
What I intend with this code is that the change of widget does so with an effect: "fade out".
If I print the "self " and the "index " receiving QStackedWidget.setCurrentIndex shows the following:
<__main__.StackedWidget object at 0x7fc2eb6b5c18> 0
The number zero is index, and the other element is self
Thank you for your attention, I hope someone can help.
Your question isn't completely clear, but don't you just want:
def setIndex(self, index):
self.setCurrentIndex(index)
However, this is a little redundant as you should able to link the button directly to the setCurrentIndex method and use lambda to pass the index value:
btfr.clicked.connect(lambda: self.setCurrentIndex(2))

PyQt4 - Using a QItemDelegate to display widget in a QListView

I want to have a QListView which displays custom widgets. I guess the best way to do this would be a QItemDelegate. Unfortunately I don't quite understand how to subclass it correctly and how to implement the paint() method, which seems to be the most important one. I couldn't find anything about using a delegate to create another widget.
I already tried to implement something similar without a delegate, but that didn't work out that well, because QListView is not supposed to display widgets.
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
class Model(QtCore.QAbstractListModel):
def __init__(self, parent=None):
super(QtCore.QAbstractListModel, self).__init__(parent)
self._widgets = []
def headerData(self, section, orientation, role):
""" Returns header for columns """
return "Header"
def rowCount(self, parentIndex=QtCore.QModelIndex()):
""" Returns number of interfaces """
return len(self._widgets)
def data(self, index, role):
""" Returns the data to be displayed """
if role == QtCore.Qt.DisplayRole:
row = index.row()
return self._widgets[row]
def insertRow(self, widget, parentIndex=QtCore.QModelIndex()):
""" Inserts a row into the model """
self.beginInsertRows(parentIndex, 0, 1)
self._widgets.append(widget)
self.endInsertRows()
class Widget(QtGui.QWidget):
def __init__(self, parent=None, name="None"):
super(QtGui.QWidget, self).__init__(parent)
self.layout = QtGui.QHBoxLayout()
self.setLayout(self.layout)
self.checkbox = QtGui.QCheckBox()
self.button = QtGui.QPushButton(self)
self.label = QtGui.QLabel(self)
self.label.setText(name)
self.layout.addWidget(self.checkbox)
self.layout.addWidget(self.button)
self.layout.addWidget(self.label)
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(QtGui.QMainWindow, self).__init__(parent)
self.view = QtGui.QListView(self)
self.model = Model()
self.view.setModel(self.model)
self.setCentralWidget(self.view)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.show()
app = QtGui.QApplication(sys.argv)
window = Window()
sys.exit(app.exec_())
So, how would I need to implement a delegate in order to do what I want?
Here's an example of a QTableWidget with a button and text on each row. I defined an add_item method to add a whole row at once: insert a new row, put a button in column 0, put a regular item in column 1.
import sys
from PyQt4 import QtGui,QtCore
class myTable(QtGui.QTableWidget):
def __init__(self,parent=None):
super(myTable,self).__init__(parent)
self.setColumnCount(2)
def add_item(self,name):
#new row
row=self.rowCount()
self.insertRow(row)
#button in column 0
button=QtGui.QPushButton(name)
button.setProperty("name",name)
button.clicked.connect(self.on_click)
self.setCellWidget(row,0,button)
#text in column 1
self.setItem(row,1,QtGui.QTableWidgetItem(name))
def on_click(self):
# find the item with the same name to get the row
text=self.sender().property("name")
item=self.findItems(text,QtCore.Qt.MatchExactly)[0]
print("Button click at row:",item.row())
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
widget = myTable()
widget.add_item("kitten")
widget.add_item("unicorn")
widget.show()
sys.exit(app.exec_())
Bonus: how to know on which button did the user clicked ? A button doesn't have a row property, but we can create one when we instantiate the buttons, like so:
button.setProperty("row",row)
Problem is, if you sort your table or delete a row, the row numbers will not match any more. So instead we set a "name" property, same as the text of the item in column 1. Then we can use findItems to get the row (see on_click).

PyQt4 QAbstractListModel - Only first data widget is displayed

I'm trying to implement the QAbstractListModel class in order to display several similar widgets.
The following code shows my problem:
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
class Model(QtCore.QAbstractListModel):
def __init__(self, parent=None):
super(QtCore.QAbstractListModel, self).__init__(parent)
self._widgets = []
def headerData(self, section, orientation, role):
""" Returns header for columns """
return "bla"
def rowCount(self, parentIndex=QtCore.QModelIndex()):
""" Returns number of interfaces """
return len(self._widgets)
def data(self, index, role):
""" Returns the data to be displayed """
if role == QtCore.Qt.DisplayRole:
row = index.row()
return self._widgets[row]
def insertRow(self, widget, parentIndex=QtCore.QModelIndex()):
""" Inserts a row into the model """
self.beginInsertRows(parentIndex, 0, 1)
self._widgets.append(widget)
self.endInsertRows()
class Widget(QtGui.QWidget):
def __init__(self, parent=None, name="None"):
super(QtGui.QWidget, self).__init__(parent)
self.layout = QtGui.QHBoxLayout()
self.setLayout(self.layout)
self.checkbox = QtGui.QCheckBox()
self.button = QtGui.QPushButton(self)
self.label = QtGui.QLabel(self)
self.label.setText(name)
self.layout.addWidget(self.checkbox)
self.layout.addWidget(self.button)
self.layout.addWidget(self.label)
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(QtGui.QMainWindow, self).__init__(parent)
self.view = QtGui.QListView(self)
self.model = Model()
self.view.setModel(self.model)
self.setCentralWidget(self.view)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.show()
app = QtGui.QApplication(sys.argv)
window = Window()
sys.exit(app.exec_())
It works, there are four clickable entries in the list, but in only one of them the widget is actually displayed. Why is that?
I guess this behaviour is either caused by data() or how I'm using beginInsertRows(), but I can't figure out where the error is.
ìnsertRow() function now looks like that
def insertRow(self, widget, parentIndex=QtCore.QModelIndex()):
""" Inserts a row into the model """
self.beginInsertRows(parentIndex, len(self._widgets), len(self._widgets))
self._widgets.append(widget)
self.endInsertRows()
but it still does not work.
Actually, the four widgets are displayed. The issue is, they're all displayed in the top left corner. You can see they overlap if you put names, here "1", "2", "3", "4":
Fixing the row numbers doesn't solve the issue. The widgets will be in the correct rows but will still be displayed on the top left. It is because data is supposed to return text for the display role.
To display simple widgets, I suggest using QListWidget and the setItemWidget method. Otherwise you'll have to use delegates.
self.beginInsertRows(parentIndex, 0, 1)
0 - start
1 - end
You refresh only first row during insert
self.beginInsertRows(parentIndex, len(self._widgets), len(self._widgets))
must be work. Don't remember this method
self.model.reset()
this refresh all list, without specific rows

How to stop QTreeWidget from creating the item duplicates on Drag and Drop

The code below creates QTreeWidget with five items.
The self.setDragDropMode(self.InternalMove) flag assures that when the item is dragged on top of
another there will be no copy of it made (so the number of items always stay the same).
If we replace this line with self.setDragDropMode(self.DragDrop) then every time an item is dragged/dropped a new copy of will be created.
Since I don't want a copy of item to be created on every dragAndDrop event I would be happy with InternalMove flag if it wouldn't be blocking QTreeWidget from accepting the drops from outside of its own view (if InternalMove flag is set QTreeWidget does not allow dragging-dropping from another QTreeWidget, QListView or File Browser).
Is there a way to set an override so QTreeWidget doesn't create a duplicate of dragged item and yet allows a dropping from outside of its own window.
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])
class Tree(QtGui.QTreeWidget):
def __init__(self, *args, **kwargs):
super(Tree, self).__init__()
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(self.InternalMove)
items=[QtGui.QTreeWidgetItem([name]) for name in ['Item_1','Item_2','Item_3','Item_4','Item_5']]
self.addTopLevelItems(items)
self.resize(360,240)
self.show()
tree=Tree()
sys.exit(app.exec_())
The key to solving this problem is that you have to implement when the object has moved to the next QListsWidget and check whether or not the data is duplicated or not. Take the data from source to destination by removing the source and adding this data to destination QListsWidget.
Use two methods, dragEnterEvent and dropEvent, to handle them all;
Implemented dragEnterEvent Check object to move is same QListsWidget.
Implemented dropEvent Check data is duplicated or not And take data from source to destination.
Example:
import sys
from PyQt4 import QtCore, QtGui
class QCustomTreeWidget (QtGui.QTreeWidget):
def __init__(self, parent = None):
super(QCustomTreeWidget, self).__init__(parent)
self.setDragEnabled(True)
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.resize(360,240)
def dragEnterEvent (self, eventQDragEnterEvent):
sourceQCustomTreeWidget = eventQDragEnterEvent.source()
if isinstance(sourceQCustomTreeWidget, QCustomTreeWidget):
if self != sourceQCustomTreeWidget:
sourceQCustomTreeWidget.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
eventQDragEnterEvent.accept()
else:
sourceQCustomTreeWidget.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
QtGui.QTreeWidget.dragEnterEvent(self, eventQDragEnterEvent)
else:
QtGui.QTreeWidget.dragEnterEvent(self, eventQDragEnterEvent)
def dropEvent (self, eventQDropEvent):
sourceQCustomTreeWidget = eventQDropEvent.source()
if isinstance(sourceQCustomTreeWidget, QCustomTreeWidget):
if self != sourceQCustomTreeWidget:
sourceQCustomTreeWidget.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
sourceQTreeWidgetItem = sourceQCustomTreeWidget.currentItem()
isFound = False
for column in range(0, self.columnCount()):
sourceQString = sourceQTreeWidgetItem.text(column)
listsFoundQTreeWidgetItem = self.findItems(sourceQString, QtCore.Qt.MatchExactly, column)
if listsFoundQTreeWidgetItem:
isFound = True
break
if not isFound:
(sourceQTreeWidgetItem.parent() or sourceQCustomTreeWidget.invisibleRootItem()).removeChild(sourceQTreeWidgetItem)
self.invisibleRootItem().addChild(sourceQTreeWidgetItem)
else:
sourceQCustomTreeWidget.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
QtGui.QTreeWidget.dropEvent(self, eventQDropEvent)
else:
QtGui.QTreeWidget.dropEvent(self, eventQDropEvent)
class QCustomQWidget (QtGui.QWidget):
def __init__ (self, parent = None):
super(QCustomQWidget, self).__init__(parent)
self.my1QCustomTreeWidget = QCustomTreeWidget(self)
self.my2QCustomTreeWidget = QCustomTreeWidget(self)
items = [QtGui.QTreeWidgetItem([name]) for name in ['Item_1', 'Item_2', 'Item_3', 'Item_4', 'Item_5']]
self.my1QCustomTreeWidget.addTopLevelItems(items)
self.allQHBoxLayout = QtGui.QHBoxLayout()
self.allQHBoxLayout.addWidget(self.my1QCustomTreeWidget)
self.allQHBoxLayout.addWidget(self.my2QCustomTreeWidget)
self.setLayout(self.allQHBoxLayout)
app = QtGui.QApplication([])
myQCustomQWidget = QCustomQWidget()
myQCustomQWidget.show()
sys.exit(app.exec_())
Useful reference for event handle

Categories