How to enable button after QListWidget is no longer empty - python

I would like my button to be disabled until there are items actually in my QListWidget. I have tried if and while statements in my AppDemo class but I feel like it needs to change in the ListBoxWidget class, however the listBoxWidget is already a sub class of the AppDemo.
Example Code:
import sys, os
from PyQt5.QtWidgets import QApplication, QMainWindow, QListWidget, QListWidgetItem, QPushButton
from PyQt5.QtCore import Qt, QUrl
class ListBoxWidget(QListWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptDrops(True)
self.resize(600, 600)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
if url.isLocalFile():
links.append(str(url.toLocalFile()))
else:
links.append(str(url.toString()))
self.addItems(links)
else:
event.ignore()
class AppDemo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(1200, 600)
self.listbox_view = ListBoxWidget(self)
self.btn = QPushButton('Get Value', self)
self.btn.setEnabled(False)
self.btn.setGeometry(850, 400, 200, 50)
self.btn.clicked.connect(lambda: print(self.getSelectedItem()))
def getSelectedItem(self):
item = QListWidgetItem(self.listbox_view.currentItem())
return item.text()
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
sys.exit(app.exec_())

You have to use the signals that are emitted when the number of rows of the model associated with the view changes, those signals must invoke a method that updates the state of the button based on the number of items in the QListWidget:
class AppDemo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(1200, 600)
self.listbox_view = ListBoxWidget(self)
self.listbox_view.model().modelReset.connect(self.handle_rows_changed)
self.listbox_view.model().rowsInserted.connect(self.handle_rows_changed)
self.listbox_view.model().rowsRemoved.connect(self.handle_rows_changed)
self.listbox_view.model().layoutChanged.connect(self.handle_rows_changed)
self.btn = QPushButton("Get Value", self)
self.btn.setEnabled(False)
self.btn.setGeometry(850, 400, 200, 50)
self.btn.clicked.connect(lambda: print(self.getSelectedItem()))
def getSelectedItem(self):
item = self.listbox_view.currentItem()
return item.text() if item is not None else ""
def handle_rows_changed(self):
self.btn.setEnabled(bool(self.listbox_view.count()))

Related

Calling functions between PyQt5 classes in Python

I'm trying to call a function in the main class with the PyQt5 button "dropEvent" event in Python. Although the "print("setText")" command in the function works, the next "self.lbl_1.setText("setText")" command does not work.
Code:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Button(QPushButton):
def __init__(self, title, parent):
super(Button, self).__init__(title, parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat('text/plain'):
event.accept()
else:
event.ignore()
def dropEvent(self, event):
self.setText(event.mimeData().text())
MainWindow().lbl_setText()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 200, 150)
self.setWindowTitle("Example")
self.setup()
def setup(self):
self.btn_quit = Button('Quit', self)
self.btn_quit.clicked.connect(QApplication.instance().quit)
self.btn_quit.resize(self.btn_quit.sizeHint())
self.btn_quit.move(90, 100)
self.btn_quit.setAcceptDrops(True)
self.le_drag = QLineEdit('', self)
self.le_drag.setDragEnabled(True)
self.le_drag.move(50, 50)
self.lbl_1= QLabel('Hi', self)
self.lbl_1.move(50, 10)
def closeEvent(self, event: QCloseEvent):
reply = QMessageBox.question(self, 'Message', "r u sure!",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def lbl_setText(self):
print("setText")
self.lbl_1.setText("setText")
def main():
app = QApplication([])
app.setStyle("Fusion")
mainWin = MainWindow()
mainWin.show()
app.exec()
if __name__ == '__main__':
main()
The interaction does not occur between classes but between objects, in your case you are creating a new MainWindow object that is not visible so you have that problem. A simple way to communicate objects in Qt is through signals and slots:
class Button(QPushButton):
dropped = pyqtSignal(str)
# ....
def dropEvent(self, event):
self.setText(event.mimeData().text())
self.dropped.emit(self.text())
class MainWindow(QMainWindow):
# ...
def setup(self):
self.btn_quit = Button('Quit', self)
self.btn_quit.clicked.connect(QApplication.quit)
self.btn_quit.resize(self.btn_quit.sizeHint())
self.btn_quit.move(90, 100)
self.btn_quit.setAcceptDrops(True)
self.le_drag = QLineEdit('', self)
self.le_drag.setDragEnabled(True)
self.le_drag.move(50, 50)
self.lbl_1= QLabel('Hi', self)
self.lbl_1.move(50, 10)
self.btn_quit.dropped.connect(self.lbl_1.setText) # <---
# ...

Getting drag and drop target pyqt5

I am working on a drag and drop GUI in pyqt5 and am trying to get the target widget of the drag and drop operation but when i try the target() function of the QDrag object i returns <main.MainWindow object at 0x0000025FDAC09EE0> and I dont know how to use that. I want to access the index of the widget in a QGridLayout so that I can make the two widgets swap places.
Here is my code:
import sys
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QPushButton, QWidget, QApplication, QGridLayout, QScrollArea, QMainWindow, QSlider
class Stroj:
def __init__(self, rok, naziv, trajanje):
self.rok = rok
self.naziv = naziv
self.trajanje = trajanje
class Button(QPushButton):
drag = 0
def __init__(self, title, parent):
super().__init__(title, parent)
def mouseMoveEvent(self, e):
if e.buttons() != Qt.LeftButton:
return
mimeData = QMimeData()
mimeData.setText(self.text())
self.drag = QDrag(self)
self.drag.setMimeData(mimeData)
self.drag.setPixmap(self.grab())
self.drag.setHotSpot(self.rect().center())
dropAction = self.drag.exec_(Qt.MoveAction)
class MainWindow(QMainWindow):
layout = QGridLayout()
btns = []
snd = ""
i = 0
j = 0
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setAcceptDrops(True)
self.scroll = QScrollArea()
self.widget = QWidget()
self.drag = QDrag(self)
SL = []
for x in range(30):
self.btns.append(x)
for x in range(30):
self.btns[x] = Button(str(x), self)
self.btns[x].setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.layout.addWidget(self.btns[x], self.i, self.j)
if(self.j > 5):
self.j = 0
self.i += 1
else:
self.j += 1
self.widget.setLayout(self.layout)
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.widget)
self.setCentralWidget(self.scroll)
self.setWindowTitle('Raspored')
self.setGeometry(350, 75, 950, 750)
def dragEnterEvent(self, e):
self.snd = e.mimeData().text()
e.accept()
def dragMoveEvent(self, e):
e.accept()
def dropEvent(self, e):
sender = self.snd
position = e.pos()
position.setX(int(position.x() - self.btns[int(sender)].width() / 2))
position.setY(int(position.y() - self.btns[int(sender)].height() / 2))
self.btns[int(sender)].move(position)
print(self.layout.indexOf(e.source()))
print(e.source().drag.target())
e.setDropAction(Qt.MoveAction)
e.accept()
def main():
app = QApplication(sys.argv)
main = MainWindow()
main.show()
app.exec_()
if __name__ == '__main__':
main()
The target of a drop event is always the widget that receives the drop action, so it's pretty obvious that if you intercept the event from the main window instance, you'll get the main window as target.
If you need to find the widget at a specific position, you need to use QApplication.widgetAt(pos).
In the following example, modified from the given code, I'm accepting the dragEnter/dragMove events only when the source is a Button instance, and the target is not the same. Then I switch those buttons using their position in the layout.
class MainWindow(QMainWindow):
# ...
def dragEnterEvent(self, e):
e.accept()
def dragMoveEvent(self, e):
source = e.source()
target = QApplication.widgetAt(self.mapToGlobal(e.pos()))
if (isinstance(e.source(), Button) and isinstance(target, Button) and target != source):
e.accept()
else:
e.ignore()
def dropEvent(self, e):
source = e.source()
target = QApplication.widgetAt(self.mapToGlobal(e.pos()))
if (not isinstance(source, Button) or not isinstance(target, Button)
or target == source):
return
layout = self.widget.layout()
sourceIndex = layout.indexOf(source)
sourcePos = layout.getItemPosition(sourceIndex)
targetIndex = layout.indexOf(target)
targetPos = layout.getItemPosition(targetIndex)
layout.addWidget(source, *targetPos)
layout.addWidget(target, *sourcePos)
e.accept()
Consider that this is a very simple implementation: you should also ensure that the widgets are actually children of the same window and are in the same layout.

error when close with effect fade window pyqt5

I have a bit when try change new window UI with effect fade. I added effect on closeEvent of mainwindow but it doen't work.
This is my code:
library used:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import uic
load ui
uifile_1 = 'home.ui'
form_1, base_1 = uic.loadUiType(uifile_1)
uifile_2 = 'plate.ui'
form_2, base_2 = uic.loadUiType(uifile_2)
Class Home page:
class HomePage(base_1, form_1):
def __init__(self):
super(base_1,self).__init__()
self.setupUi(self)
#add button for click next page
self.btn_start = QPushButton(self)
self.btn_start.clicked.connect(self.change)
self._heightMask = self.height()
self.animation = QPropertyAnimation(self, b"heightPercentage")
self.animation.setDuration(1000)
self.animation.setStartValue(self.height())
self.animation.setEndValue(-1)
self.animation.finished.connect(self.close)
self.isStarted = False
def change(self):
self.plate = PlatePage()
self.plate.show()
self.close()
#pyqtProperty(int)
def heightMask(self):
return self._heightMask
#heightMask.setter
def heightPercentage(self, value):
self._heightMask = value
rect = QRect(0, 0, self.width(), self.heightMask)
self.setMask(QRegion(rect))
def closeEvent(self, event):
if not self.isStarted:
self.animation.start()
self.isStarted = True
event.ignore()
else:
self.closeEvent(self, event)
Class Plate Page
class PlatePage(base_2, form_2):
def __init__(self):
super(base_2, self).__init__()
self.setupUi(self)
self.show()
Please have a look and give me some solution.
Thank You
Try it:
from PyQt5.QtCore import QPropertyAnimation, QThread
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton
class Window(QWidget):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
self.resize(400, 400)
layout = QVBoxLayout(self)
layout.addWidget(QPushButton('Button', self))
self.animation = QPropertyAnimation(self, b'windowOpacity')
self.animation.setDuration(1000)
self.isStarted = False
self.doShow()
def doShow(self):
try:
self.animation.finished.disconnect(self.close)
except:
pass
self.animation.stop()
self.animation.setStartValue(0)
self.animation.setEndValue(1)
self.animation.start()
def closeEvent(self, event):
if not self.isStarted:
self.animation.stop()
self.animation.finished.connect(self.close)
self.animation.setStartValue(1)
self.animation.setEndValue(0)
self.animation.start()
self.isStarted = True
event.ignore()
else:
event.accept()
if __name__ == '__main__':
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())

PyQt - Custom scrolling with QListWidget

I am trying to figure out a way to customize the scrollbars for QListWidget to have the scrollbars above and below the QListWidget instead of the normal vertical and horizontal scrollbars.
Please check out my example below if you don't understand what I mean.
In the example below I use QPushButtons with QTimers controlling the scrolling in place of the scrollbars but what I am looking for are scrollbars like the ones in QMenu when menu scrolling is enabled.
If that is not an option, I am wondering if there is a scrollbar signal or something that I could try to use to know when the scrollbars are normally activated? That way I can show/hide the buttons as needed. Thanks.
import sys
from PyQt5.QtCore import pyqtSignal, QTimer, Qt
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout, \
QApplication, QStyle, QListWidget, QStyleOptionButton, QListWidgetItem
class UpBtn(QPushButton):
mouseHover = pyqtSignal()
def __init__(self):
QPushButton.__init__(self)
self.setMouseTracking(True)
self.timer = QTimer()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
opt = QStyleOptionButton()
self.initStyleOption(opt)
self.style().drawControl(QStyle.CE_ScrollBarSubLine, opt, painter, self)
painter.end()
def startScroll(self):
self.mouseHover.emit()
def enterEvent(self, event):
self.timer.timeout.connect(self.startScroll)
self.timer.start(120)
def leaveEvent(self, event):
self.timer.stop()
class DwnBtn(QPushButton):
mouseHover = pyqtSignal()
def __init__(self):
QPushButton.__init__(self)
self.setMouseTracking(True)
self.timer = QTimer()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
opt = QStyleOptionButton()
self.initStyleOption(opt)
self.style().drawControl(QStyle.CE_ScrollBarAddLine, opt, painter, self)
painter.end()
def startScroll(self):
self.mouseHover.emit()
def enterEvent(self, event):
self.timer.timeout.connect(self.startScroll)
self.timer.start(120)
def leaveEvent(self, event):
self.timer.stop()
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.layout = QVBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
self.upBtn = UpBtn()
self.upBtn.setFixedWidth(230)
self.layout.addWidget(self.upBtn)
self.listWidget = QListWidget()
self.listWidget.setFixedWidth(230)
self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.listWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.layout.addWidget(self.listWidget)
self.downBtn = DwnBtn()
self.downBtn.setFixedWidth(230)
self.layout.addWidget(self.downBtn)
self.setLayout(self.layout)
self.upBtn.clicked.connect(self.upBtnClicked)
self.upBtn.mouseHover.connect(self.upBtnClicked)
self.downBtn.clicked.connect(self.downBtnClicked)
self.downBtn.mouseHover.connect(self.downBtnClicked)
for i in range(100):
item = QListWidgetItem()
item.setText("list item " + str(i))
self.listWidget.addItem(item)
def upBtnClicked(self):
cur = self.listWidget.currentRow()
self.listWidget.setCurrentRow(cur - 1)
def downBtnClicked(self):
cur = self.listWidget.currentRow()
self.listWidget.setCurrentRow(cur + 1)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
EDIT:
Here is an example image for what I am talking about. This is a scrollable QMenu.
EDIT:
Scrollable QMenu code.
Uncomment the commented parts to get a fixed size like in the image. Normally Qmenu scrolling only works when the menu items exceed the screen height. I am just looking for the top and bottom hover style scrolling but to be used in QListWidget.
import sys
from PyQt5.QtCore import QPoint, QEvent
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout, \
QApplication, QAction, QMenu, QProxyStyle, QStyle
class MyMenu(QMenu):
def event(self, event):
if event.type() == QEvent.Show:
self.move(self.parent().mapToGlobal(QPoint(-108, 0)))
return super(MyMenu, self).event(event)
# class CustomStyle(QProxyStyle):
# def pixelMetric(self, QStyle_PixelMetric, option=None, widget=None):
# if QStyle_PixelMetric == QStyle.PM_MenuScrollerHeight:
# return 15
# if QStyle_PixelMetric == QStyle.PM_MenuDesktopFrameWidth:
# return 290
# else:
# return QProxyStyle.pixelMetric(self, QStyle_PixelMetric, option, widget)
class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.layout = QVBoxLayout()
self.btn = QPushButton("Button")
self.btn.setFixedHeight(30)
self.btn.setFixedWidth(100)
self.myMenu = MyMenu("Menu", self.btn)
self.btn.setMenu(self.myMenu)
self.layout.addWidget(self.btn)
self.setLayout(self.layout)
menus = []
for _ in range(5):
myMenus = QMenu("Menu"+str(_+1), self.btn)
# myMenus.setFixedHeight(120)
myMenus.setStyleSheet("QMenu{menu-scrollable: 1; }")
menus.append(myMenus)
for i in menus:
self.btn.menu().addMenu(i)
for item in range(100):
action = QAction("item" + str(item), self)
i.addAction(action)
if __name__ == '__main__':
app = QApplication(sys.argv)
# app.setStyle(CustomStyle())
w = MainWindow()
w.show()
app.exec_()
The idea is to obtain the row of the upper and lower element that will decide whether the buttons are hidden or not, for that we use the method itemAt () that returns the item given the geometrical coordinates. On the other hand I have improved this calculation has to do every time they change the number of items in the QListView for that we use the signals of the internal model.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Button(QtWidgets.QPushButton):
moveSignal = QtCore.pyqtSignal()
def __init__(self, *args, **kwargs):
super(Button, self).__init__(*args, **kwargs)
self.m_timer = QtCore.QTimer(self, interval=120)
self.m_timer.timeout.connect(self.moveSignal)
self.setMouseTracking(True)
self.setFixedHeight(20)
def mouseReleaseEvent(self, e):
super(Button, self).mousePressEvent(e)
self.setDown(True)
def enterEvent(self, e):
self.setDown(True)
self.m_timer.start()
super(Button, self).enterEvent(e)
def leaveEvent(self, e):
self.setDown(False)
self.m_timer.stop()
super(Button, self).leaveEvent(e)
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.setFixedWidth(230)
icon = self.style().standardIcon(QtWidgets.QStyle.SP_ArrowUp)
self.upBtn = Button(icon=icon)
self.upBtn.moveSignal.connect(self.moveUp)
icon = self.style().standardIcon(QtWidgets.QStyle.SP_ArrowDown)
self.downBtn = Button(icon=icon)
self.downBtn.moveSignal.connect(self.moveDown)
self.listWidget = QtWidgets.QListWidget()
self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.listWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
layout = QtWidgets.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addWidget(self.upBtn)
layout.addWidget(self.listWidget)
layout.addWidget(self.downBtn)
self.adjust_buttons()
self.create_connections()
def create_connections(self):
self.listWidget.currentItemChanged.connect(self.adjust_buttons)
model = self.listWidget.model()
model.rowsInserted.connect(self.adjust_buttons)
model.rowsRemoved.connect(self.adjust_buttons)
model.rowsMoved.connect(self.adjust_buttons)
model.modelReset.connect(self.adjust_buttons)
model.layoutChanged.connect(self.adjust_buttons)
#QtCore.pyqtSlot()
def adjust_buttons(self):
first = self.listWidget.itemAt(QtCore.QPoint())
r = self.listWidget.row(first)
self.upBtn.setVisible(r != 0 and r!= -1)
last = self.listWidget.itemAt(self.listWidget.viewport().rect().bottomRight())
r = self.listWidget.row(last)
self.downBtn.setVisible( r != (self.listWidget.count() -1) and r != -1)
#QtCore.pyqtSlot()
def moveUp(self):
ix = self.listWidget.moveCursor(QtWidgets.QAbstractItemView.MoveUp, QtCore.Qt.NoModifier)
self.listWidget.setCurrentIndex(ix)
#QtCore.pyqtSlot()
def moveDown(self):
ix = self.listWidget.moveCursor(QtWidgets.QAbstractItemView.MoveDown, QtCore.Qt.NoModifier)
self.listWidget.setCurrentIndex(ix)
#QtCore.pyqtSlot(str)
def add_item(self, text):
item = QtWidgets.QListWidgetItem(text)
self.listWidget.addItem(item)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
for i in range(100):
window.add_item("item {}".format(i))
window.show()
sys.exit(app.exec_())

Drag and Drop QLabels with PyQt5

I'm trying to drag and drop a Qlabel on another Qlabel with PyQt5:
from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QHBoxLayout, QVBoxLayout, QGridLayout,QFrame, QComboBox, QLabel, QLineEdit
from PyQt5.QtGui import QIcon, QFont, QPixmap, QImage
import sys
class my_label(QLabel):
def __init__(self,title,parent):
super().__init__(title,parent)
self.setAcceptDrops(True)
def dragEnterEvent(self,event):
if event.mimeData().hasFormat("text/plain"):
event.accept()
else:
event.ignore()
def dropEvent(self,event):
self.setText(event.mimeData().text())
class application(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
label = my_label("drop there",self)
label.resize(100,100)
label.move(190,65)
label_to_drag = QLabel("drag this",self)
#label_to_drag.setDragEnabled(True) #doesn't work with QLabel
self.show()
def closeEvent(self,event):
message = QMessageBox.question(self,"Message","Quit ?",QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
if message == QMessageBox.Yes:
event.accept()
else:
event.ignore()
app = QApplication(sys.argv)
fenetre = application()
sys.exit(app.exec_())
I wanted to make my first label "draggable",by calling the setDragEnabled(True) method (as i was doing for QLineEdit),and drop it on the second label to change his text. Dropping text from another app is working fine,but I can't find how to drag the QLabel inside my own app...
What did I miss ?
EDIT : modified the code to try to Drag&Drop Images :
class DraggableLabel(QLabel):
def __init__(self,parent,image):
super(QLabel,self).__init__(parent)
self.setPixmap(QPixmap(image))
self.show()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drag_start_position = event.pos()
def mouseMoveEvent(self, event):
if not (event.buttons() & Qt.LeftButton):
return
if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
return
drag = QDrag(self)
mimedata = QMimeData()
mimedata.setText(self.text())
drag.setMimeData(mimedata)
pixmap = QPixmap(self.size())
painter = QPainter(pixmap)
painter.drawPixmap(self.rect(), self.grab())
painter.end()
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos())
drag.exec_(Qt.CopyAction | Qt.MoveAction)
class my_label(QLabel):
def __init__(self,title,parent):
super().__init__(title,parent)
self.setAcceptDrops(True)
def dragEnterEvent(self,event):
if event.mimeData().hasFormat("text/plain"):
print("event accepted")
event.accept()
else:
print("event rejected")
event.ignore()
def dropEvent(self,event):
if event.mimeData().hasImage():
self.setPixmap(QPixmap.fromImage(QImage(event.mimeData().imageData())))
class application(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
label_to_drag = DraggableLabel(self,"index.jpg")
label = my_label("drop there",self)
label.resize(100,100)
label.move(190,65)
self.show()
When I drop the DraggableLabel (displaying the image) on my_label,the event is accepted, but hasImage() always returns false...Is the way I set the image up wrong ?
In the case of QLabel you must create everything from the beginning, for this you can follow the examples of the docs.
In the following example I have placed an example where one class only accepts the drop and the other the drag so that you can see each part and understand better.
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
from PyQt5.QtGui import QDrag, QPixmap, QPainter, QCursor
from PyQt5.QtCore import QMimeData, Qt
class DraggableLabel(QLabel):
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drag_start_position = event.pos()
def mouseMoveEvent(self, event):
if not (event.buttons() & Qt.LeftButton):
return
if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
return
drag = QDrag(self)
mimedata = QMimeData()
mimedata.setText(self.text())
drag.setMimeData(mimedata)
pixmap = QPixmap(self.size())
painter = QPainter(pixmap)
painter.drawPixmap(self.rect(), self.grab())
painter.end()
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos())
drag.exec_(Qt.CopyAction | Qt.MoveAction)
class DropLabel(QLabel):
def __init__(self, *args, **kwargs):
QLabel.__init__(self, *args, **kwargs)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasText():
event.acceptProposedAction()
def dropEvent(self, event):
pos = event.pos()
text = event.mimeData().text()
self.setText(text)
event.acceptProposedAction()
class Widget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
label = DropLabel("drop there",self)
label.setGeometry(190, 65, 100,100)
label_to_drag = DraggableLabel("drag this",self)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Update:
Do not confuse the QDrag with the QMimeData, if you want to use imageData() you must set it with setImageData() as indicated by the docs:
class DraggableLabel(QLabel):
def __init__(self,parent,image):
super(QLabel,self).__init__(parent)
self.setPixmap(QPixmap(image))
self.show()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drag_start_position = event.pos()
def mouseMoveEvent(self, event):
if not (event.buttons() & Qt.LeftButton):
return
if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
return
drag = QDrag(self)
mimedata = QMimeData()
mimedata.setText(self.text())
mimedata.setImageData(self.pixmap().toImage())
drag.setMimeData(mimedata)
pixmap = QPixmap(self.size())
painter = QPainter(pixmap)
painter.drawPixmap(self.rect(), self.grab())
painter.end()
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos())
drag.exec_(Qt.CopyAction | Qt.MoveAction)
class my_label(QLabel):
def __init__(self,title,parent):
super().__init__(title,parent)
self.setAcceptDrops(True)
def dragEnterEvent(self,event):
if event.mimeData().hasImage():
print("event accepted")
event.accept()
else:
print("event rejected")
event.ignore()
def dropEvent(self,event):
if event.mimeData().hasImage():
self.setPixmap(QPixmap.fromImage(QImage(event.mimeData().imageData())))

Categories

Resources