PyQt5 Custom widget does not appear in GridLayout [duplicate] - python

This question already has answers here:
Simple python inheritance
(3 answers)
QtDesigner changes will be lost after redesign User Interface
(2 answers)
Closed 4 years ago.
I am trying to add a custom widget to a layout. I can successfully add many PushButtons to my GridLayout, but when I attempt to add the custom widget it does not show.
I have attempted to provide a minimal example:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class moduleForm(QtWidgets.QWidget):
def __init__(self, parent = None):
self.parent = parent
self.setObjectName("moduleForm")
self.resize(300, 400)
self.fModule = QtWidgets.QPushButton("Test")
self.fModule.setGeometry(QtCore.QRect(0, 0, 80, 20))
self.retranslateUi(self.parent)
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self, moduleForm):
_translate = QtCore.QCoreApplication.translate
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("Rb Controller")
MainWindow.resize(900, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.loMainTab = QtWidgets.QHBoxLayout(self.centralwidget)
self.centralwidget.setLayout(self.loMainTab)
self.saChannels = QtWidgets.QScrollArea(self.centralwidget)
self.saChannels.setWidgetResizable(True)
self.saChannels.setGeometry(QtCore.QRect(10,10,10,10))
self.fButtons = QtWidgets.QFrame(self.centralwidget)
self.fButtons.setFrameShadow(QtWidgets.QFrame.Sunken)
self.pbAddModule = QtWidgets.QPushButton(self.fButtons)
self.pbAddModule.setGeometry(QtCore.QRect(10, 10, 80, 20))
self.pbAddModule.setObjectName("pbAddModule")
self.loButtons = QtWidgets.QHBoxLayout(self.fButtons)
self.loButtons.addWidget(self.pbAddModule)
self.loButtons.addStretch()
self.fButtons.setLayout(self.loButtons)
self.hlwChannelsContents = QtWidgets.QWidget()
self.hlwChannelsContents.setObjectName("hlwChannelsContents")
self.hloChannelsContents = QtWidgets.QHBoxLayout(self.hlwChannelsContents)
self.hloChannelsContents.setObjectName("hloChannelsContents")
self.gloChannelsContents = QtWidgets.QGridLayout()
self.hloChannelsContents.addLayout(self.gloChannelsContents)
self.saChannels.setWidget(self.hlwChannelsContents)
self.loMainTab.addWidget(self.fButtons)
self.loMainTab.addWidget(self.saChannels,1)
for ii in range(10):
for jj in range(10):
self.r_button = QtWidgets.QPushButton("Element %s,%s " % (ii, jj))
self.gloChannelsContents.addWidget(self.r_button,ii,jj)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.pbAddModule.clicked.connect(self.createModule)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Rb Controller"))
self.pbAddModule.setText(_translate("MainWindow", "Add Module"))
def createModule(self):
createModule = moduleForm()
self.gloChannelsContents.addWidget(createModule)
createModule.show()
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super(ApplicationWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def main():
app = QtWidgets.QApplication(sys.argv)
application = ApplicationWindow()
application.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I have added the super().__init__ function but it is still not working. The PushButton in my custom widget gets displayed if I add it not the custom widget, so all the other code is fine.
If I have:
self.gloChannelsContents.addWidget(createModule.fModule,self.i,self.j)
in createModule then I get a dynamic PushButton, however, if I try to use the custom widget
self.gloChannelsContents.addWidget(createModule,self.i,self.j)
nothing appears.

Try it:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class moduleForm(QtWidgets.QWidget):
def __init__(self, row, parent = None): # + row
super().__init__()
self.parent = parent
self.setObjectName("moduleForm")
self.resize(300, 400)
self.fModule = QtWidgets.QPushButton("Test {}".format(row)) # + row
self.fModule.setGeometry(QtCore.QRect(0, 0, 80, 20))
self.retranslateUi(self.parent)
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self, moduleForm):
_translate = QtCore.QCoreApplication.translate
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.i = 11 # + self.i
MainWindow.setObjectName("Rb Controller")
MainWindow.resize(900, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.loMainTab = QtWidgets.QHBoxLayout(self.centralwidget)
self.centralwidget.setLayout(self.loMainTab)
self.saChannels = QtWidgets.QScrollArea(self.centralwidget)
self.saChannels.setWidgetResizable(True)
self.saChannels.setGeometry(QtCore.QRect(10,10,10,10))
self.fButtons = QtWidgets.QFrame(self.centralwidget)
self.fButtons.setFrameShadow(QtWidgets.QFrame.Sunken)
self.pbAddModule = QtWidgets.QPushButton(self.fButtons)
self.pbAddModule.setGeometry(QtCore.QRect(10, 10, 80, 20))
self.pbAddModule.setObjectName("pbAddModule")
self.loButtons = QtWidgets.QHBoxLayout(self.fButtons)
self.loButtons.addWidget(self.pbAddModule)
self.loButtons.addStretch()
self.fButtons.setLayout(self.loButtons)
self.hlwChannelsContents = QtWidgets.QWidget()
self.hlwChannelsContents.setObjectName("hlwChannelsContents")
self.hloChannelsContents = QtWidgets.QHBoxLayout(self.hlwChannelsContents)
self.hloChannelsContents.setObjectName("hloChannelsContents")
self.gloChannelsContents = QtWidgets.QGridLayout()
self.hloChannelsContents.addLayout(self.gloChannelsContents)
self.saChannels.setWidget(self.hlwChannelsContents)
self.loMainTab.addWidget(self.fButtons)
self.loMainTab.addWidget(self.saChannels,1)
for ii in range(10):
for jj in range(10):
self.r_button = QtWidgets.QPushButton("Element %s,%s " % (ii, jj))
self.gloChannelsContents.addWidget(self.r_button, ii, jj)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.pbAddModule.clicked.connect(self.createModule)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Rb Controller"))
self.pbAddModule.setText(_translate("MainWindow", "Add Module"))
def createModule(self):
self.createModule = moduleForm(self.i) # +
self.gloChannelsContents.addWidget(self.createModule.fModule, self.i, 0) # +
self.i += 1 # +
# self.createModule.show() # ???
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super(ApplicationWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def main():
app = QtWidgets.QApplication(sys.argv)
application = ApplicationWindow()
application.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

Related

Passing string from one window to another using Signal

I am trying pass a string from First window to Second window using signal. I want the string to be shown after pressing the push button on the Second window. However, I am getting the following error:"TypeError: decorated slot has no signature compatible with clicked(bool)"
I am using Qt-designer to create First and Second window.
Below is the main code:
class First(QDialog):
signal = pyqtSignal(str)
def __init__(self, parent = None):
super(First, self).__init__(parent)
self.ui = Ui_First()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.Send)
self.show()
def Send(self):
UserInput = self.ui.lineEdit.text()
foo = Second()
self.signal.connect(foo.Receive)
self.signal.emit(str(UserInput))
self.ui = Second()
class Second(QDialog):
def __init__(self, parent = None):
super(Second, self).__init__(parent)
self.ui = Ui_Second()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.Receive)
self.show()
#pyqtSlot(str)
def Receive(self, strA):
self.ui.label.setText(strA)
Here is the First.py:
class Ui_First(object):
def setupUi(self, First):
First.setObjectName("First")
First.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(First)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(First)
self.lineEdit.setGeometry(QtCore.QRect(40, 40, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(First)
QtCore.QMetaObject.connectSlotsByName(First)
def retranslateUi(self, First):
_translate = QtCore.QCoreApplication.translate
First.setWindowTitle(_translate("First", "First"))
self.pushButton.setText(_translate("First", "Send to Second"))
Here is the Second.py:
class Ui_Second(object):
def setupUi(self, Second):
Second.setObjectName("Second")
Second.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(Second)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(Second)
self.label.setGeometry(QtCore.QRect(60, 40, 55, 16))
self.label.setObjectName("label")
self.retranslateUi(Second)
QtCore.QMetaObject.connectSlotsByName(Second)
def retranslateUi(self, Second):
_translate = QtCore.QCoreApplication.translate
Second.setWindowTitle(_translate("Second", "Second"))
self.pushButton.setText(_translate("Second", "Show Input"))
self.label.setText(_translate("Second", "TextLabel"))
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Ui_First(object):
def setupUi(self, First):
First.setObjectName("First")
First.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(First)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(First)
self.lineEdit.setGeometry(QtCore.QRect(40, 40, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(First)
QtCore.QMetaObject.connectSlotsByName(First)
def retranslateUi(self, First):
_translate = QtCore.QCoreApplication.translate
First.setWindowTitle(_translate("First", "First"))
self.pushButton.setText(_translate("First", "Send to Second"))
class Ui_Second(object):
def setupUi(self, Second):
Second.setObjectName("Second")
Second.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(Second)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(Second)
self.label.setGeometry(QtCore.QRect(60, 40, 55, 16))
self.label.setObjectName("label")
self.retranslateUi(Second)
QtCore.QMetaObject.connectSlotsByName(Second)
def retranslateUi(self, Second):
_translate = QtCore.QCoreApplication.translate
Second.setWindowTitle(_translate("Second", "Second"))
self.pushButton.setText(_translate("Second", "Show Input"))
self.label.setText(_translate("Second", "TextLabel"))
class First(QDialog):
signal = pyqtSignal(str)
def __init__(self, parent = None):
super(First, self).__init__(parent)
self.ui = Ui_First()
self.ui.setupUi(self)
self.ui.lineEdit.setFocus() # +
self.ui.pushButton.clicked.connect(self.Send)
self.show()
def Send(self):
UserInput = self.ui.lineEdit.text()
foo = Second(self) # + self.
self.signal.emit(str(UserInput))
# self.signal.connect(foo.Receive)
# self.ui = Second()
class Second(QDialog):
def __init__(self, parent = None):
super(Second, self).__init__(parent)
self.ui = Ui_Second()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.close) # - (self.Receive)
parent.signal.connect(self.Receive) # +++
self.show()
#pyqtSlot(str)
def Receive(self, strA):
self.ui.label.setText(strA)
self.ui.label.adjustSize() # +
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = First()
gui.show()
sys.exit(app.exec_())

Expand item in QTreeView with QFileSystemModel

I need to going to some directory when user click on button.
User enter path in QInputDialog (for example /mnt/data/Music on linux), and program go to this directory, like M-c in Midnight Commander or cd in ranger, but i don't know how i can do this... I already know all the documentation by heart
main.py
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QMainWindow, QInputDialog
import exampleQTV
class PyMap(QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.search.clicked.connect(self.searchAction)
def searchAction(self):
text, ok = QInputDialog.getText(self, "Go to", "Enter path")
if ok:
path = text.split("/")
for item in path:
if item != "":
print("ITEM:", item)
self.leftView.keyboardSearch(item)
self.leftView.setExpanded(self.leftView.currentIndex(), True)
print("currentIndex():",self.leftView.model.filePath(self.leftView.currentIndex()))
child = self.leftView.currentIndex().child(0,0)
print("child:", self.leftView.model.filePath(child))
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.leftView = exampleQTV.exampleQTV()
self.leftView.setObjectName("leftView")
self.gridLayout.addWidget(self.leftView, 1, 0, 1, 1)
self.search = QtWidgets.QPushButton(self.centralwidget)
self.search.setObjectName("select")
self.gridLayout.addWidget(self.search, 0, 0, 1, 2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.search.setText(_translate("MainWindow", "Search"))
def main():
app = QtWidgets.QApplication(sys.argv)
window = PyMap()
window.show()
app.exec_()
if __name__ == '__main__':
main()
exampleQTV.py
from PyQt5.QtWidgets import QTreeView, QFileSystemModel
from PyQt5.QtCore import QDir
class exampleQTV(QTreeView):
def __init__(self):
QTreeView.__init__(self)
self.model = QFileSystemModel()
self.model.setRootPath(QDir.rootPath())
self.setModel(self.model)
self.eventCalled = False
self.requestForEscape = False
self.setColumnHidden(1, True)
self.setColumnHidden(2, True)
self.setColumnHidden(3, True)
self.expandAll()
If you want an item to be expanded your ancestors must be expanded, in the following code you implement that logic:
import sys
from PyQt5 import QtCore, QtWidgets
def expandPath(index, view):
if not index.isValid():
return
indexes = []
ix = index
while ix.isValid():
indexes.insert(0, ix)
ix = ix.parent()
for ix in indexes:
view.expand(ix)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
model = QtWidgets.QFileSystemModel()
model.setRootPath(QtCore.QDir.rootPath())
view = QtWidgets.QTreeView()
view.setModel(model)
view.setRootIndex(model.index(QtCore.QDir.rootPath()))
doc_directory = QtCore.QStandardPaths.writableLocation(
QtCore.QStandardPaths.DocumentsLocation
)
ix = model.index(doc_directory)
expandPath(ix, view)
view.resize(640, 480)
for i in (1, 2, 3):
view.setColumnHidden(i, True)
view.show()
sys.exit(app.exec_())

TAB key is not working in my code in PYQT5 and Python

What I need from the program is, once I press the TAB from the keyboard, should move to the next field and execute specific function.
The function in the first field is 'ID'(digits) is taken from the user as input. Then, after I press the TAB should extract specific digits, these digits are the 'Birth-date'.
By the 'push-button' is working fine. However, by the tab key is not working and through errors. Please see the code and the image.
I am using PYQT5 and Python 3.7.
Form image
See the for image in this link:
The code
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(282, 130, 181, 41))
self.lineEdit.setObjectName("lineEdit")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(216, 140, 51, 20))
self.Handel_Buttons()
self.keyPressEvent()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "ID"))
self.label_2.setText(_translate("MainWindow", "D.O.B"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
def Handel_Buttons(self):
self.pushButton.clicked.connect(self.ID)
def keyPressEvent(self):
print('HI')
if QtCore.Qt.Key_Tab:
self.ID()
def ID(self):
number = self.lineEdit.text()
#number = '279121100762'
#print(int(number[5]))
digit = int(number[5])
digit1 = int(number[6])
digit2 = int(number[3])
digit3 = int(number[4])
digit4 = int(number[1])
digit5 = int(number[2])
#self.textBrowser.append(str[digit,digit1])
self.textBrowser.append ('%d%d/%d%d/19%d%d' % (digit, digit1,digit2,digit3,digit4,digit5))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Many thanks,
The code you provide can not be executed so I take the time to create it from scratch. The basic idea is to intercept the events of the QLineEdit through an eventFilter:
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.id_le = QtWidgets.QLineEdit("279121100762")
self.id_le.installEventFilter(self)
self.dob_le = QtWidgets.QLineEdit()
btn = QtWidgets.QPushButton(
text="Press me",
clicked=self.conversion
)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QFormLayout(central_widget)
lay.addRow("ID", self.id_le)
lay.addRow("D.O.B", self.dob_le)
lay.addRow(btn)
def eventFilter(self, obj, event):
if self.id_le == obj and event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Tab:
QtCore.QTimer.singleShot(0, self.conversion)
return super(MainWindow, self).eventFilter(obj, event)
def conversion(self):
id_value = self.id_le.text()
if len(id_value) > 7:
text = id_value[1:7]
dt = QtCore.QDateTime.fromString(text, "yyddMM")
if dt.isValid():
self.dob_le.setText(dt.toString("dd/MM/yyyy"))
return
print("Invalid conversion")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

PyDesigner PyQt5 MouseEvent Not working setMouseTracking(True)

How to let MouseEvent working?
I try to print mouse tracking to label x,y coordinate but always fail. I already using setMouseTracking(True), generate from QtDesigner ui to py.
code Below:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(640, 480)
Form.setMouseTracking(True)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(270, 190, 58, 15))
self.label.setObjectName("label")
self.label.setMouseTracking(True)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "TextLabel"))
def mouseMoveEvent(self, e):
x = e.x()
y = e.y()
text = "x: {0}, y: {1}".format(x, y)
self.label.setText(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
Ui_Form is not a widget, so it will not have the mouseMoveEvent method, as the PyQt docs point out you must create a class that inherits the appropriate widget, in this case QWidget, and use the interface provided by Qt Designer:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(640, 480)
Form.setMouseTracking(True)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(270, 190, 58, 15))
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "TextLabel"))
class Form(QtWidgets.QWidget, Ui_Form):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setupUi(self)
self.setMouseTracking(True)
def mouseMoveEvent(self, e):
text = "x: {0}, y: {1}".format(e.x(), e.y())
self.label.setText(text)
self.label.adjustSize()
super(Form, self).mouseMoveEvent(e)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Form()
w.show()
sys.exit(app.exec_())

How to paint over a child widget?

So I have this Ui_MainWindow class generated by pyuic5.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 450)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.canvas = QtWidgets.QWidget(self.centralWidget)
self.canvas.setGeometry(QtCore.QRect(70, 30, 621, 341))
self.canvas.setAutoFillBackground(False)
self.canvas.setObjectName("canvas")
self.gview = QtWidgets.QGraphicsView(self.canvas)
self.gview.setGeometry(QtCore.QRect(80, 50, 256, 192))
self.gview.setObjectName("gview")
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menuBar.setObjectName("menuBar")
self.menuhola = QtWidgets.QMenu(self.menuBar)
self.menuhola.setObjectName("menuhola")
self.menust = QtWidgets.QMenu(self.menuBar)
self.menust.setObjectName("menust")
MainWindow.setMenuBar(self.menuBar)
self.menuBar.addAction(self.menuhola.menuAction())
self.menuBar.addAction(self.menust.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuhola.setTitle(_translate("MainWindow", "hola"))
self.menust.setTitle(_translate("MainWindow", "splendid"))
And I want to paint on something, as long as it's not the main window. However, no matter what I try, it just doesn't work.
Here's my code:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPainter
from src.qt_design.main_window import Ui_MainWindow
class SystemApp(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def paintEvent(self, event):
# Nope
painter = QPainter(self.ui.gview)
painter.drawLine(0, 0, 50, 50)
# Nope
painter = QPainter(self.ui.canvas)
painter.drawLine(0, 0, 50, 50)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = SystemApp()
window.show()
sys.exit(app.exec_())
I'm not sure if I should either:
1. Paint with this parent on its children (like what I tried above)
2. Override children's paintEvent, but it's maybe a bad idea, see here
Any help will be appreciated!
You can get what you are trying to accomplish with an event filter
class SystemApp(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.gview.installEventFilter(self)
self.ui.canvas.installEventFilter(self)
def eventFilter(self, obj, e):
if e.type() == QtCore.QEvent.Paint:
painter = QPainter()
painter.begin(obj)
if obj == self.ui.canvas:
painter.setPen(QtCore.Qt.red) # Some specific painting
painter.drawLine(0, 0, 50, 50)
painter.end()
return True
return super().eventFilter(obj, e)

Categories

Resources