I'm trying to figure out how dnd works with (py)qt. I tried several example applications and.. hm was wondering: how do I see what data is actually inside a drag/drop event? I tried printing the event, the dict of the event, the mimeData().text().. but no mater what i drag in there, there seems to be no data whatsoever. Eg if I drag over a '.desktop' file from /usr/share/applications, shouldn't there be info inside the drag event?
see this eg. application:
#!/usr/bin/python
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtCore import Qt
class DragFromWidget(QtGui.QDockWidget):
def __init__(self, parent=None):
super(DragFromWidget, self).__init__(parent=parent)
self.layout().addWidget(QtGui.QLabel("Label!"))
class DragToWidget(QtGui.QDockWidget):
def __init__(self, parent=None):
super(DragToWidget, self).__init__(parent=parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
#HOW?
print event
print event.__dict__
print event.mimeData()
print event.mimeData().__dict__
print event.mimeData().text()
event.accept()
def dropEvent(self, event):
#HOW?
print event
print event.__dict__
print event.mimeData()
print event.mimeData().__dict__
print event.mimeData().text()
class SandboxApp(QtGui.QApplication):
def __init__(self, *args, **kwargs):
super(SandboxApp, self).__init__(*args)
self.mainwindow = MainWindow()
self.mainwindow.show()
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
self.setDockOptions(QtGui.QMainWindow.AllowNestedDocks|QtGui.QMainWindow.AnimatedDocks)
self.addDockWidget(Qt.LeftDockWidgetArea, DragFromWidget())
self.addDockWidget(Qt.RightDockWidgetArea, DragToWidget())
def main():
app = SandboxApp(sys.argv)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Related
I have the following code but it's complaining that I cannot access the UI data from my thread. In my example code below, What is the best way I can access the userInputString value so my threading can run?
self.nameField is a PyQt QLineEdit.
QObject::setParent: Cannot set parent, new parent is in a different thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QWidget::repaint: Recursive repaint detected
import myUI
class MainUIClass(QtGui.QMainWindow, myUI.Ui_MainWindow):
def __init__(self, parent=None):
super(MainUIClass, self).__init__(parent)
self.setupUi(self)
self.startbutton.clicked.connect(self.do_work)
self.workerThread = WorkerThread()
self.connect(self.workerThread, SIGNAL("myThreading()"), self.myThreading, Qt.DirectConnection)
def do_work(self):
self.userInputString = self.nameField.Text()
self.workerThread.start()
def myThreading(self):
if userInputString is not None:
#Do something
class WorkerThread(QThread):
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
def run(self):
self.emit(SIGNAL("myThreading()"))
if __name__ == '__main__':
a = QtGui.QApplication(sys.argv)
app = MainUIClass()
app.show()
a.exec_()
Not sure if it's what you need but here is a working QThread exemple using Qt5
import time
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.worker_thread = WorkerThread()
self.worker_thread.job_done.connect(self.on_job_done)
self.create_ui()
def create_ui(self):
self.button = QtWidgets.QPushButton('Test', self)
self.button.clicked.connect(self.start_thread)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
def start_thread(self):
self.worker_thread.gui_text = self.button.text()
self.worker_thread.start()
def on_job_done(self, generated_str):
print("Generated string : ", generated_str)
self.button.setText(generated_str)
class WorkerThread(QtCore.QThread):
job_done = QtCore.pyqtSignal('QString')
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
self.gui_text = None
def do_work(self):
for i in range(0, 1000):
print(self.gui_text)
self.job_done.emit(self.gui_text + str(i))
time.sleep(0.5)
def run(self):
self.do_work()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
test = MainWindow()
test.show()
app.exec_()
Assuming that I have a QPushButton named button, I successfully do the following to allow click event:
class UI(object):
def setupUi(self, Dialog):
# ...
self.button.clicked.connect(self.do_something)
def do_something(self):
# Something here
My question is: how can I call do_something() when the tab key is pressed? For instance, if I have a QlineEdit named tb_id, after entering a value and press tab key, do_something() method should be called in the same way as what clicked does above. How can I do that using pyqt5?
Thank you so much.
To get what you want there are many methods but before pointing it by observing your code I see that you have generated it with Qt Designer so that code should not be modified but create another class that uses that code so I will place the base code:
from PyQt5 import QtCore, QtWidgets
class UI(object):
def setupUi(self, Dialog):
self.button = QtWidgets.QPushButton("Press Me")
lay = QtWidgets.QVBoxLayout(Dialog)
lay.addWidget(self.button)
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
#QtCore.pyqtSlot()
def do_something(self):
print("do_something")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
Also, I recommend you read the difference between event and signal in the world of Qt in What are the differences between event and signal in Qt since you speak of click event but in the world of Qt one must say clicked signal.
Now if going to the point there are the following options:
Using keyPressEvent:
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
#QtCore.pyqtSlot()
def do_something(self):
print("do_something")
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Tab:
self.do_something()
Using an event filter:
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
#QtCore.pyqtSlot()
def do_something(self):
print("do_something")
def eventFilter(self, obj, event):
if obj is self and event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Tab:
self.do_something()
return super(Dialog, self).eventFilter(obj, event)
Using activated signal of QShorcut:
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
shortcut = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab), self)
shortcut.activated.connect(self.do_something)
#QtCore.pyqtSlot()
def do_something(self):
print("do_something")
From the previous methods I prefer the latter because you do not need to overwrite anything and you can connect to several functions.
On the other hand, only events are detected when the focus is in the Qt window.
I assume you put your widget in QDialog widget, so if you want to implement your own key press event, you should override the keyPressEvent of your Dialog widget,
then it can behave as you like.
Here's an example,
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog
class UI(QDialog):
def __init__(self):
super(UI, self).__init__()
# ...
self.button.clicked.connect(self.do_something)
def do_something(self):
# Something here
def keyPressEvent(self, event):
# when press key is Tab call your function
if event.key() == Qt.Key_Tab:
self.do_something()
Example code I am using:
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.open_about = False
self.openAction = QtWidgets.QAction('About', self)
self.openAction.triggered.connect(self.aboutDialog)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.calendar = QtWidgets.QCalendarWidget(self)
self.setCentralWidget(self.calendar)
def about_state_upd(self, value):
self.open_about = value
def aboutDialog(self):
self._about = AboutDialog(self)
self._about.exec_()
def hideEvent(self, hideEvent):
if self.open_about == True:
self._about.setVisible(False)
def showEvent(self, showEvent):
if self.open_about == True:
if self._about.isHidden() == True:
self._about.setModal(True)
self._about.setVisible(True)
class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent):
super(AboutDialog, self).__init__(parent)
self.setMinimumSize(400, 350)
self.parent().about_state_upd(True)
def closeEvent(self, closeEvent):
self.parent().about_state_upd(False)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
sys.exit(app.exec_())
This code basically works, but seems very complicated. Is there a simpler / cleaner way to make it so that when the modal QDialog is open, if the QMainWindow is minimized, the QDialog also gets minimized too (and reverse when QMainWindow is restored)?
Code is running on KDE Neon (Kubuntu-based distro).
May be you can use this: http://korbinin.blogspot.fr/search/label/minimize%20button
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainForm(QDialog):
def __init__(self, fn=None,parent=None):
super(MainForm, self).__init__(parent,\
flags=Qt.WindowMinimizeButtonHint|Qt.WindowMaximizeButtonHint)
Thanks to the people on the PyQt Mailing list, I managed to get a workaround for KDE. Instead of using exec_(), I am just using show() - then I use setDisabled() on QMainWindow to make dialog act in a modal fashion. Here is a (very quick and basic) example for anyone interested:
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.openAction = QtWidgets.QAction('About', self)
self.openAction.triggered.connect(self.aboutDialog)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.calendar = QtWidgets.QCalendarWidget(self)
self.setCentralWidget(self.calendar)
def aboutDialog(self):
self._about = AboutDialog(self)
self.setDisabled (True)
self._about.show()
def enableWidgets(self):
self.setDisabled(False)
class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent):
super(AboutDialog, self).__init__(parent)
self.setMinimumSize(400, 350)
def closeEvent(self, parent):
self.parent().enableWidgets()
def changeEvent(self, event):
if event.type() == QtCore.QEvent.WindowStateChange:
if self.windowState() & QtCore.Qt.WindowMinimized:
self.parent().showMinimized()
else:
self.parent().showMaximized()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
sys.exit(app.exec_())
Link to PyQt Mailing List posts.
I need to enable a button in my app whenever something is dropped to my custom QTreeWidget.
I sub-classed QTreeWidget to implement drag and drop of custom data. But I'm not able to find a way to get notified when something is dropped into my custom QTreeWidget. I couldn't find a QTreeWidget signal to do this. Of course, the QTreeWidget's dropEvent() will be called each time something is dropped but that doesn't help much to achieve what I'm trying to do.
Here's where I instantiate the custom QTreeWidget that accepts drops from another widget,
from PyQt4 import QtCore, QtGui
import MyTreeWidget
class TestWindow(QtGui.QDialog):
def __init__(self, parent=None):
super(TestWindow, self).__init__(parent)
self.myTreeWidget = MyTreeWidget.MyTreeWidget()
...
#self.myTreeWidget.onItemDropped.connect(self.doSomethingOnItemDropped) <== I am looking for something like this
def doSomethingOnItemDropped(self):
# Enable certain button
...
And then, here is how I sub-classed QTreeWidget,
import sys
from PyQt4 import QtGui, QtCore
class MyTreeWidget(QtGui.QTreeWidget):
def __init__(self, parent=None):
super(MyTreeWidget, self).__init__(parent)
self.setAcceptDrops(True)
def dropEvent(self, event):
if (event.mimeData().hasFormat('application/x-icon-and-text')):
event.acceptProposedAction()
data = event.mimeData().data("application/x-icon-and-text")
stream= QtCore.QDataStream(data, QtCore.QIODevice.ReadOnly)
text = QtCore.QString()
icon = QtGui.QIcon()
stream >> text >> icon
item = QtGui.QTreeWidgetItem(self)
item.setText(0, text)
item.setIcon(0, icon)
self.addTopLevelItem(item)
else:
event.ignore()
def dragEnterEvent(self, event):
if (event.mimeData().hasFormat('application/x-icon-and-text')):
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasFormat("application/x-icon-and-text"):
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore()
Any ideas? Thanks!
UPDATE : This is what worked for me
Based on comment by #ekhumoro I defined a custom signal itemDropped for my custom QTreeWidget which emits in dropEvent() event handler.
import sys
from PyQt4 import QtGui, QtCore
class MyTreeWidget(QtGui.QTreeWidget):
itemDropped = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(MyTreeWidget, self).__init__(parent)
self.setAcceptDrops(True)
def dropEvent(self, event):
if (event.mimeData().hasFormat('application/x-icon-and-text')):
event.acceptProposedAction()
data = event.mimeData().data("application/x-icon-and-text")
stream= QtCore.QDataStream(data, QtCore.QIODevice.ReadOnly)
text = QtCore.QString()
icon = QtGui.QIcon()
stream >> text >> icon
item = QtGui.QTreeWidgetItem(self)
item.setText(0, text)
item.setIcon(0, icon)
self.addTopLevelItem(item)
self.itemDropped.emit()
else:
event.ignore()
And in my app,
from PyQt4 import QtCore, QtGui
import MyTreeWidget
class TestWindow(QtGui.QDialog):
def __init__(self, parent=None):
super(TestWindow, self).__init__(parent)
self.myTreeWidget = MyTreeWidget.MyTreeWidget()
self.myTreeWidget.itemDropped.connect(self.doSomethingOnItemDropped)
...
def doSomethingOnItemDropped(self):
# Enable certain button
...
You could define a custom signal and emit it from dropEvent:
class MyTreeWidget(QtGui.QTreeWidget):
itemDropped = QtCore.pyqtSignal()
def dropEvent(self, event):
if (event.mimeData().hasFormat('application/x-icon-and-text')):
...
self.itemDropped.emit()
In PySide2 you can use this:
class MyTreeWidget(QtGui.QTreeWidget):
itemDropped = QtCore.Signal()
def dropEvent(self, event):
if (event.mimeData().hasFormat('application/x-icon-and-text')):
self.itemDropped.emit()
I have a button and two tablewidgets.Pressing the button does two different things depending on which one of the tablewidgets was activated before the push of the button.How can I get the right widget?
You could for example use the focusInEvent to store the activated widget and return it when pressing the button, something like this:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore
class MyTableWidget(QtGui.QTableWidget):
focusIn = QtCore.pyqtSignal(QtCore.QObject)
def __init__(self, parent=None):
super(MyTableWidget, self).__init__(parent)
def focusInEvent(self, event):
self.focusIn.emit(self)
return super(MyTableWidget, self).focusInEvent(event)
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.lastFocusedTableWidget = None
self.tableWidgetFirst = MyTableWidget(self)
self.tableWidgetFirst.setObjectName("tableWidgetFirst")
self.tableWidgetFirst.focusIn.connect(self.on_tableWidget_focusIn)
self.tableWidgetSecond = MyTableWidget(self)
self.tableWidgetSecond.setObjectName("tableWidgetSecond")
self.tableWidgetSecond.focusIn.connect(self.on_tableWidget_focusIn)
self.pushButtonLastFocused = QtGui.QPushButton(self)
self.pushButtonLastFocused.setText("Print the last focused QTableWidget!")
self.pushButtonLastFocused.clicked.connect(self.on_pushButtonLastFocused_clicked)
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.tableWidgetFirst)
self.layoutVertical.addWidget(self.tableWidgetSecond)
self.layoutVertical.addWidget(self.pushButtonLastFocused)
#QtCore.pyqtSlot(QtCore.QObject)
def on_tableWidget_focusIn(self, obj):
self.lastFocusedTableWidget = obj
#QtCore.pyqtSlot()
def on_pushButtonLastFocused_clicked(self):
print self.lastFocusedTableWidget.objectName()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.resize(333, 111)
main.show()
sys.exit(app.exec_())