I created a widget in qt designer and transformed the ui file using pyuic to a python class called Ui_wid_canvas. This is supposed to be used as special canvas:
# file mgcanvas.py
from PyQt4 import QtCore, QtGui
class Ui_wid_canvas(object):
def setupUi(self, wid_canvas):
wid_canvas.setObjectName("wid_canvas")
wid_canvas.resize(400, 300)
self.horizontalLayout = QtGui.QHBoxLayout(wid_canvas)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton = QtGui.QPushButton(wid_canvas)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.retranslateUi(wid_canvas)
QtCore.QMetaObject.connectSlotsByName(wid_canvas)
def retranslateUi(self, wid_canvas):
wid_canvas.setWindowTitle(QtGui.QApplication.translate("wid_canvas", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("wid_canvas", "PushButton", None, QtGui.QApplication.UnicodeUTF8))
From Ui_wid_canvas I derive a class MyCanvas to implement the paintEvent function and some utility functions such as moo(). Within the paintevent all it shall do is draw two rects. If I use the following class as my application everything works like a charm.
# file mycanvas.py
from PyQt4 import QtCore, QtGui
import mgcanvas
class MyCanvas(mgcanvas.Ui_wid_canvas, QtGui.QWidget):
def __init__(self):
super(mgcanvas.Ui_wid_canvas, self).__init__()
self.setupUi(self)
def paintEvent(self, qpaintevent):
print "PaintEvent canvas"
painter = QtGui.QPainter(self)
painter.setBrush(QtGui.QColor(255,0,0,80))
painter.setPen(QtGui.QColor(00,00,00,255))
painter.drawRect(10,10,100,100)
r = QtCore.QRectF(110,110,100,100)
painter.drawRect(r)
painter.drawText(r,"Hello", QtGui.QTextOption(QtCore.Qt.AlignCenter))
def moo(self):
print "This is canvas mooing"
Now, when I create an application Test instantiating MyCanvas (see below), the paintEvent for Test is called, but the paintevent for MyCanvcas is never called, the rects are not drawn and no output "Paintevent Canvas" on the console. If I call self.widget.update() or self.widget.redraw() in Test.paintevent() the paintevent is not caught. If I call self.widget.paintevent() manually, the function is called, but the painter not activated. The pushbutton, on the other hand, is shown from which I figure that the widget is included correctly, but just not the paint event is called by the child widget.
# file test.py; executed with `python test.py`
from PyQt4 import QtCore, QtGui
import mycanvas
class Test(object):
def setupUi(self, Gui):
self.counter = 0
Gui.setObjectName("TestObject")
Gui.resize(500,500)
self.layout = QtGui.QVBoxLayout()
self.widget = mycanvas.MyCanvas()
self.widget.setupUi(self)
self.widget.setObjectName("wid_canvas")
self.layout.addWidget(self.widget)
self.retranslateUi(Gui)
QtCore.QMetaObject.connectSlotsByName(Gui)
def retranslateUi(self, Gui):
Gui.setWindowTitle(QtGui.QApplication.translate("TestObject", "Title", None, QtGui.QApplication.UnicodeUTF8))
def paintEvent(self, qpaintevent):
print "---> Enter"
self.counter += 1
print "counter", self.counter
self.widget.repaint()
self.widget.moo()
print "<-- Leave"
class MyTest(Test, QtGui.QWidget):
def __init__(self):
super(Test, self).__init__()
self.setupUi(self)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
ui = MyTest()
ui.show()
sys.exit(app.exec_())
Setting the Qt.WA_PaintOutsidePaintEvent is not an option, because it does not work on Mac and Windows but I'd like to stay platform independent.
Please excuse me posting so much code, but I guess it will make things easier. I tried to keep it to a minimum. Can someone tell me how I can have the Widget MyCanvas paint on itself and include this painting widget in another widget MyTest, which will work as the application?
In you class Test, you didn't attach the layout to the parameter Gui, by passing it as parameter to QVBoxLayout, and you called the self.widget.setupUi for MyCanvas although it was already called by MyCanvas constructor.
class Test(object):
def setupUi(self, Gui):
self.counter = 0
Gui.setObjectName("TestObject")
Gui.resize(500,500)
self.layout = QtGui.QVBoxLayout(Gui)
self.widget = mycanvas.MyCanvas()
self.widget.setObjectName("wid_canvas")
self.layout.addWidget(self.widget)
self.retranslateUi(Gui)
QtCore.QMetaObject.connectSlotsByName(Gui)
Related
AttributeError: type object 'QThread' has no attribute 'create'
Here is my code.
from PyQt5.QtCore import QThread
def fun(num):
print(num)
thread1 = QThread.create(fun)
thread1.start()
But Qt documentation says there is a function called create since Qt 5.10. I am using PyQt5 5.11.3. Someone please help me with this.
You can use worker objects by moving them to the thread using QObject::moveToThread().
from PyQt5.QtCore import QObject, pyqtSignal, QThread, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QProgressBar, QPushButton
class Worker(QObject):
valueChanged = pyqtSignal(int) # Value change signal
def run(self):
print('thread id ->', int(QThread.currentThreadId()))
for i in range(1, 101):
print('value =', i)
self.valueChanged.emit(i)
QThread.msleep(100)
class Window(QWidget):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
layout = QVBoxLayout(self)
self.progressBar = QProgressBar(self)
self.progressBar.setRange(0, 100)
layout.addWidget(self.progressBar)
layout.addWidget(QPushButton('Open thread', self, clicked=self.onStart))
# Current thread id
print('main id = ', int(QThread.currentThreadId()))
# Start thread update progress bar value
self._thread = QThread(self)
self._worker = Worker()
self._worker.moveToThread(self._thread) # Move to thread to execute
self._thread.finished.connect(self._worker.deleteLater)
self._worker.valueChanged.connect(self.progressBar.setValue)
def onStart(self):
print('main id -> ', int(QThread.currentThreadId()))
self._thread.start() # Start thread
QTimer.singleShot(1, self._worker.run)
def closeEvent(self, event):
if self._thread.isRunning():
self._thread.quit()
del self._thread
del self._worker
super(Window, self).closeEvent(event)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Window()
w.show()
w.setWindowTitle('Demo moveToThread')
sys.exit(app.exec_())
I have this code:
import sys, random, pprint
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5 import QtGui
from PyQt5.QtCore import Qt
class Window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(QtCore.QRect(200, 200, 700, 700))
self.widget = QtWidgets.QWidget(self)
self.widget.setGeometry(QtCore.QRect(10, 10, 400, 200))
self.widget.setObjectName("widget")
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self.widget)
self.drawPoints(painter)
painter.end()
def drawPoints(self, painter):
#drawing code
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
What do i expect: area (400x200) which would be painted by drawPoints(). QWidget inherits QPaintDevice. So this code should work. But console says:
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::end: Painter not active, aborted
Could you help me, please.
It looks like you are attempting to replicate this example, correct?
The major difference appears to be that you are defining paintEvent() for the main window, rather than the widget you are actually trying to paint. It would work if you created a custom subclass of QWidget, defined paintEvent() there, and then inserted that into a standard QMainWindow instance, like this:
class MyWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setGeometry(QtCore.QRect(10, 10, 400, 200))
self.setObjectName("widget")
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
self.drawPoints(painter)
painter.end()
def drawPoints(self, painter):
pass
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
my_window = QtWidgets.QMainWindow()
my_window.setGeometry(QtCore.QRect(200, 200, 700, 700))
my_window.setCentralWidget(MyWidget(my_window))
my_window.show()
sys.exit(app.exec_())
At the very least, it isn't printing that error message anymore.
I have a PyQt widget that sends signals with numpy.ndarray data. And I have another PyQt widget that has a slot with numpy.ndarray data.
Both widget are located on my main window, that is compiled from *.ui file. The widgets are set as promoted widgets.
Cannot I somehow connect the signal and slot in Qt Creator?
Just now it gives me the next error:
TypeError: C++ type 'ndarray' is not supported as a slot argument type
Reason for this is Qt only support the datatype defined in QMetaType passed as argument of signal, looks here http://pyqt.sourceforge.net/Docs/PyQt4/qmetatype.html#Q_DECLARE_METATYPE
According to ekhumoro's POST, I update the following code, it should work for PyQt4, not tested on PyQt5.
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from numpy import *
class MyThread(QThread):
mysignal = pyqtSignal(ndarray)
def __init__(self, parent=None):
super(MyThread, self).__init__(parent)
def run(self):
while True:
QThread.msleep(100)
self.mysignal.emit(array((1, 2, 3, 4)))
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.thread = MyThread()
self.thread.mysignal.connect(self.handleSignal)
self.thread.start()
def handleSignal(self, data):
print data
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = MyWidget()
w.show()
app.exec_()
If I have an open QWebView, I like its default context menu with "Open in New Window" as an option for links. However, I can't seem to find a way to act when the user requests a link be opened in a new window. Overriding the QWebPage.createWindow method doesn't seem to work, because the method is not invoked when the user chooses to open a link in a new window.
Any recommendations? I'm using PyQt.
Example code:
class LocalWebPage(QWebPage):
def acceptNavigationRequest(self, webFrame, networkRequest, navigationType):
print '*acceptNavigationRequest**',webFrame, networkRequest, navigationType
return QWebPage.acceptNavigationRequest(self, webFrame, networkRequest, navigationType)
def createWindow(self, windowType):
print '--createWindow', windowType
return QWebPage.createWindow(self, windowType)
class Browser(Ui_MainWindow, QMainWindow):
def __init__(self, base, name):
...
self.page = LocalWebPage()
self.webViewMain = QWebView(self.centralwidget)
self.webViewMain.setPage(self.page)
...
I have the debugging prints in there to verify that createWindow is not being called.
You'll need to call the createWindow method of the QWebView yourself, for example by reimplementing the triggerAction of the QWebPage, something like this:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore, QtWebKit
class MyPage(QtWebKit.QWebPage):
def __init__(self, parent=None):
super(MyPage, self).__init__(parent)
def triggerAction(self, action, checked=False):
if action == QtWebKit.QWebPage.OpenLinkInNewWindow:
self.createWindow(QtWebKit.QWebPage.WebBrowserWindow)
return super(MyPage, self).triggerAction(action, checked)
class MyWindow(QtWebKit.QWebView):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.myPage = MyPage(self)
self.setPage(self.myPage)
def createWindow(self, windowType):
if windowType == QtWebKit.QWebPage.WebBrowserWindow:
self.webView = MyWindow()
self.webView.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
return self.webView
return super(MyWindow, self).createWindow(windowType)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
main.load(QtCore.QUrl("http://www.example.com"))
sys.exit(app.exec_())
The link that was right-clicked can be found by using hitTestContent in the contextMenuEvent method of the QWebView:
def contextMenuEvent(self, event):
pos = event.pos()
element = self.page().mainFrame().hitTestContent(pos)
link_url = str(element.linkUrl().toString())
I'm trying to show a single QTreeWidgetItem instance on 2 QTreeWidgets, which ends up the item shown only on the 1st tree without being notified. I haven't seen its API doc talks about a limitation if any. Is there a way to workaround?
#!/usr/bin/python
import os
import sys
from PySide.QtCore import QFile
from PySide.QtUiTools import QUiLoader
from PySide.QtGui import QApplication, QTreeWidget, QTreeWidgetItem, QWidget
class MyTreeWidgetItem(QTreeWidgetItem):
def __init__(self, *args):
super(MyTreeWidgetItem, self).__init__()
class MyWidget(QWidget):
def __init__(self, *args):
super(MyWidget, self).__init__()
loader = QUiLoader()
file = QFile('./src/prove_qtreewidget/qtree_mainwidget.ui')
file.open(QFile.ReadOnly)
self.widget_ui = loader.load(file, self)
file.close()
item1 = MyTreeWidgetItem(self)
item1.setText(0, 'Item 1')
_tw1 = self.widget_ui.findChild(QTreeWidget, '_tree_widget_1')
_tw2 = self.widget_ui.findChild(QTreeWidget, '_tree_widget_2')
_tw1.addTopLevelItem(item1)
_tw2.addTopLevelItem(item1)
if __name__ == '__main__':
print("Running in " + os.getcwd() + " .\n")
app = QApplication(sys.argv)
win = MyWidget()
win.show()
app.exec_()
.ui file above is available here.
Using Qt 4.8, Ubuntu 12.04
I haven't tried PyQt binding but I just assume shouldn't be any different w/o proof.
What you need is a model and a QTreeView, that's for what they are for:
Model/View Programming: Widgets do not maintain internal data containers. They access external data through a standardized interface and therefore avoid data duplication.