This question already has an answer here:
QWidget does not draw background color
(1 answer)
Closed 4 years ago.
Observe the following code
#!/usr/bin/env python3
from PyQt5 import QtWidgets as w
class MyWidget(w.QWidget): pass
app = w.QApplication([])
frame = w.QWidget()
grid = w.QGridLayout()
frame.setLayout(grid)
w1 = MyWidget()
w2 = w.QWidget()
grid.addWidget(w1)
grid.addWidget(w2)
w1.setStyleSheet("background-color: red")
w2.setStyleSheet("background-color: red")
frame.show()
app.exec_()
The resulting app doesn't produce two identical red widgets. Qt documentation implies that things like stylesheets should work just perfectly with subclassed widgets. What's wrong here?
As they comment in this post and this post so that the inheriting classes you must overwrite paintEvent():
#!/usr/bin/env python3
from PyQt5 import QtGui, QtWidgets
class MyWidget(QtWidgets.QWidget):
def paintEvent(self, event):
opt = QtWidgets.QStyleOption()
opt.initFrom(self)
p = QtGui.QPainter(self)
self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, p, self)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
frame = QtWidgets.QWidget()
grid = QtWidgets.QGridLayout(frame)
for w in (MyWidget(), QtWidgets.QWidget()):
grid.addWidget(w)
w.setStyleSheet("background-color: red")
frame.resize(640, 480)
frame.show()
sys.exit(app.exec_())
Related
This question already has answers here:
Connecting slots and signals in PyQt4 in a loop
(3 answers)
Connecting multiples signal/slot in a for loop in pyqt
(3 answers)
Closed 7 months ago.
I came across this issue when making 'QMenu' actions in a loop and assigning a connection with them. Here is an example:
import sys
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
mbar = self.menuBar()
file_menu = mbar.addMenu("File")
animals = ['Dog','Badger','Bear','Fox']
for animal in animals:
ac = file_menu.addAction(animal)
ac.triggered.connect(lambda: print(animal))
'''Even though each action is assigned a seperate connection with the current animal,
only the last animal is ever printed. Why?'''
def main():
app = QtWidgets.QApplication([sys.argv])
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
The last variable in the loop, 'Fox', is printed for all menu entries. The solution mentioned here is to use the QMenu triggered signal instead, allowing you to store the data in the action and access it that way. Like this:
import sys
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
mbar = self.menuBar()
file_menu = mbar.addMenu("File")
animals = ['Dog','Badger','Bear','Fox']
for animal in animals:
ac = file_menu.addAction(animal)
ac.setData(animal)
file_menu.triggered.connect(lambda a: print(a.data()))
def main():
app = QtWidgets.QApplication([sys.argv])
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
This works fine but is a little annoying because to work in the real world I would have to implement some sort of check to make sure I was dealing with the right sort of action, for example by making a dataclass to hold the animal and checking for that dataclass instance. But then I discovered that the following approach also works:
import sys
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
mbar = self.menuBar()
self.file_menu = mbar.addMenu("File")
animals = ['Dog','Badger','Bear','Fox']
for animal in animals:
self.make_menu_entry(animal)
def make_menu_entry(self, animal):
ac = self.file_menu.addAction(animal)
ac.triggered.connect(lambda: print(animal))
def main():
app = QtWidgets.QApplication([sys.argv])
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
So now I'm thinking that this a scope problem, but I don't understand it. Can anyone explain what's happening?
This question already has answers here:
Argument 1 has unexpected type 'NoneType'?
(2 answers)
Closed 1 year ago.
I am trying to use function when I clicked the button with below source codes:
from PySide2.QtWidgets import QApplication
from ui_interface import *
from Custom_Widgets.Widgets import *
from PyQt5.QtGui import QIcon
# from PyQt5.QtWidgets import *
from Custom_Widgets.Widgets import QCustomSlideMenu
import sys
class MainWindow(QMainWindow):
def __init__(self,parent = None):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
########################################################################
# APPLY JSON STYLESHEET
########################################################################
# self = QMainWindow class
# self.ui = Ui_MainWindow / user interface class
loadJsonStyle(self, self.ui)
########################################################################
self.show()
self.ui.pushButton_2.clicked.connect(self.my_text())
#pyqtSlot()
def on_button1(self):
print("Button #1")
def my_text(self):
index = 1
print("{0} button clicked".format(index))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
# app.setWindowIcon(QIcon(':/icons/home.ico'))
window.show()
sys.exit(app.exec_())
When I using like this:
self.ui.pushButton_2.clicked.connect(self.my_text())
When I clicked the button, does not show anything.
But if I use like this:
self.ui.pushButton_2.clicked.connect(lambda: self.my_text())
It works.
And Also when I use like this:
self.ui.pushButton_2.clicked.connect(self.on_button1())
it works.
But I dont understand why the first step does not working?
try this
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100, 600, 400)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for widgets
def UiComponents(self):
# creating a push button
button = QPushButton("CLICK", self)
# setting geometry of button
button.setGeometry(200, 150, 100, 30)
# adding action to a button
button.clicked.connect(self.clickme)
# action method
def clickme(self):
print("pressed")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
is you're looking for this???
I need to align center some labels that are inside of a QGroupBox ( I want that labels to be centered even on resizing), I tried many "solutions" but none of them worked, the QGroupBox is inside of a QGridLayout and has expanding width.
from PyQt5 import QtCore, QtWidgets, QtGui
import sys
class TestWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QHBoxLayout()
self.setLayout(layout)
group = QtWidgets.QGroupBox()
layout.addWidget(group)
group_layout = QtWidgets.QHBoxLayout()
group.setLayout(group_layout)
labelContainerWidget = QtWidgets.QWidget()
labelContainer_layout = QtWidgets.QHBoxLayout()
labelContainerWidget.setLayout(labelContainer_layout)
label1 = QtWidgets.QLabel('test1')
label2 = QtWidgets.QLabel('test2')
group_layout.setAlignment(QtCore.Qt.AlignCenter)
group_layout.addWidget(label1)
group_layout.addWidget(label2)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
form = TestWidget()
form.show()
app.exec_()
Use layout.setAlignment(QtCore.Qt.AlignCenter)
This question already has answers here:
Aligning text in QTextEdit?
(2 answers)
Closed 4 years ago.
I am doing some random choice picker where there's a place to display info user keyed in. (which I used text browser), How do I set the text to be always align center?
self.textBrowser.setText(newList + "\n\nanalyzing in ...")
QtTest.QTest.qWait(1000)
self.textBrowser.setText(newList + "\n\nanalyzing in ..." + "\n\n 3")
QTextBrowser Class Inherits: QTextEdit
QTextEdit::setAlignment(Qt::Alignment)
Sets the alignment of the current paragraph to a. Valid alignments are Qt::AlignLeft, Qt::AlignRight, Qt::AlignJustify and Qt::AlignCenter (which centers horizontally).
Sorry, I have PyQt5:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Win(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.i = 5
self.textBrowser = QtWidgets.QTextBrowser()
self.textBrowser.setAlignment(QtCore.Qt.AlignCenter) # <-------------
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.textBrowser)
self.setLayout(layout)
timer = QtCore.QTimer(self, interval=1000, timeout=self.print_out)
timer.start()
def print_out(self, string="Hello world!"):
self.textBrowser.append(string + "\n\nanalyzing in ...\n {}".format('----' * self.i))
self.i += 1
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
myWin = Win()
myWin.show()
sys.exit(app.exec_())
In the GUI, the styling applied to the QLabel is applied only upto the height of the text in it. How do I increase it to fill the available region?
You can try something like this:
from PySide import QtGui, QtCore
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
super().__init__()
layout = QtGui.QHBoxLayout()
self.setLayout(layout)
label = QtGui.QLabel('5')
label.setAutoFillBackground(True)
p = label.palette()
p.setColor(label.backgroundRole(), QtCore.Qt.red)
label.setPalette(p)
layout.addWidget(label)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()