Is there a way to put the text of a QCheckBox above the icon? - pyqt4

I have a gridlayout that holds a bunch of check boxes. I wanted to add an image to the check boxes as well as some text. The problem I am having is that the layout of a check box is left to right (check box, icon, text).
Is there a way to put the text above the icon? Not sure if using a style sheet would work for this or not or even how that would look.
Thank you.

Answer : In PyQt4. No, your can't do it.
Why ? I read source code of QCheckBox Qt4 (C++) here and here. I saw it use default QStyleOptionButton to show check box, text and icon. It's use drawControl to draw all element in QStyleOptionButton by specified config in QStyleOptionButton. Also it have LayoutDirection. And layout direction in QStyleOptionButton. I don't know in Qt4 C++ and inheritance it and swap direction icon. But in PyQt4, It's impossible to do it.
Another way ? : Yes, It have another way to solve but not directly. Your just create your own widget just like QCheckBox and disable icon in QCheckBox and make your own QLabel ot show your icon and set it with same QLayout.
Example;
import sys
from PyQt4 import QtGui, QtCore
class QCustomCheckBox (QtGui.QWidget):
stateChanged = QtCore.pyqtSignal(int)
def __init__ (self, text, parentQWidget = None):
super(QCustomCheckBox, self).__init__(parentQWidget)
self.customQCheckBox = QtGui.QCheckBox(text)
self.iconQLabel = QtGui.QLabel()
allQHBoxLayout = QtGui.QHBoxLayout()
allQHBoxLayout.addWidget(self.customQCheckBox)
allQHBoxLayout.addWidget(self.iconQLabel)
allQHBoxLayout.addStretch(1)
self.setLayout(allQHBoxLayout)
self.customQCheckBox.stateChanged.connect(self.stateChanged.emit)
def setPixmap (self, newQPixmap, width = 48, height = 48):
self.iconQLabel.setPixmap(newQPixmap.scaled(width, height, QtCore.Qt.KeepAspectRatio))
def pixmap (self):
return self.iconQLabel.pixmap()
class QCustomWidget (QtGui.QWidget):
def __init__ (self, parent = None):
super(QCustomWidget, self).__init__(parent)
allQVBoxLayout = QtGui.QVBoxLayout()
firstQCustomCheckBox = QCustomCheckBox('First Check Box')
firstQCustomCheckBox.setPixmap(QtGui.QPixmap('1.jpg'))
allQVBoxLayout.addWidget(firstQCustomCheckBox)
secondQCustomCheckBox = QCustomCheckBox('Second Check Box')
secondQCustomCheckBox.setPixmap(QtGui.QPixmap('2.jpg'))
allQVBoxLayout.addWidget(secondQCustomCheckBox)
self.setLayout(allQVBoxLayout)
if __name__ == '__main__':
myQApplication = QtGui.QApplication(sys.argv)
myQCustomWidget = QCustomWidget()
myQCustomWidget.show()
sys.exit(myQApplication.exec_())

Related

How do I add scroll function to main window in python pyqt5?

I'm trying to learn pyqt5 in python by creating a small application. For one of the windows, I need to add a vertical scroll bar to the window. Now, this window has a table made using QLabel and QLineEdit. Check the picture to get exactly how it looks like.
As you can see there are a lot of chemicals, which goes below the window screen. I have tried numerous approaches but somehow couldn't get the result. If I am able to get the scroll, all the elements get aligned one under another (QVBoxLayout) which is not the way I want the elements to be aligned.
Here's the code I'm using
class ChemicalWindow(QWidget):
def __init__(self,chemicals,data):
super().__init__()
self.layout = QVBoxLayout()
self.setWindowTitle("Chemicals")
self.setMinimumSize(QSize(600,600))
self.setStyleSheet("background-color:#eaf4f4;")
self.chemicals = chemicals
self.data = data
self.createBody()
self.createButtons()
def createBody(self):
headerLabel = QLabel('Chemicals',scroll_widget)
headerLabel.move(265,10)
headerLabel.resize(70,40)
headerLabel.setStyleSheet("color:#000;")
tcLabel = QLabel('Tc',scroll_widget)
tcLabel.move(200,50)
tcLabel.resize(60,30)
tcLabel.setStyleSheet("color:#000;")
pcLabel = QLabel('Pc',scroll_widget)
pcLabel.move(280,50)
pcLabel.resize(60,30)
pcLabel.setStyleSheet("color:#000;")
cpLabel = QLabel('Cp',scroll_widget)
cpLabel.move(360,50)
cpLabel.resize(60,30)
cpLabel.setStyleSheet("color:#000;")
self.chemical_names = self.chemicals.keys()
y_position = 90
# List for keeping chemical inputs variables in form of dict of list -> {A:[chemical_a_tc,chemical_a_pc,chemical_a_cp],
# B:[chemical_b_tc,chemical_b_pc,...],...}
self.chemical_inputs = dict()
# Creating labels for the chemical names
for name in self.chemical_names:
chemicalLabel = QLabel(name,scroll_widget)
chemicalLabel.move(70,y_position)
chemicalLabel.resize(75,30)
chemicalLabel.setStyleSheet("color:#000;")
chemicalLabel.setToolTip(name)
y_position += 40
current_chemical_inputs = dict()
for chemical_input in self.chemicals[name]:
current_chemical_inputs[chemical_input] = QLineEdit(scroll_widget)
self.chemical_inputs[name] = current_chemical_inputs
position_y = 90
for individual_chemical in self.chemical_inputs:
position_x = 160
for chemical_input in self.chemical_inputs[individual_chemical]:
self.chemical_inputs[individual_chemical][chemical_input].setText(str(self.data['chemicals'][individual_chemical][chemical_input]))
self.chemical_inputs[individual_chemical][chemical_input].move(position_x,position_y)
self.chemical_inputs[individual_chemical][chemical_input].resize(80,30)
self.chemical_inputs[individual_chemical][chemical_input].setStyleSheet("color:#000;background-color:#a9d6e5;padding:2px;")
position_x += 90
position_y += 40
def createButtons(self):
close_button = QPushButton('Close',self)
close_button.move(510,550)
close_button.resize(70,30)
close_button.setStyleSheet("background-color:#00509d;color:#fff;")
close_button.clicked.connect(self.closeButton)
def closeButton(self):
self.close()
What am I doing wrong?
Firstly, instead of using .move() to manually place your widgets, you should be using a QLayout (ex. QHBoxLayout or QVBoxLayout). This will automatically space your labels, and you can modify it by adjusting stretch and adding spacers (QSpacerItem). For more complex layouts, you can either nest multiple box layouts, or use a QGridLayout.
Now to address the scrolling:
First, you want to create your scroll area. Make this widget the central widget. Remember to set setWidgetResizable to True.
scroller = QScrollArea()
scroller.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
scroller.resize(self.width(),self.height())
scroller.setWidgetResizable(True)
self.setCentralWidget(scroller)
Next, create your container and add it to the scroll area. All your layout elements (labels, buttons, etc.) should be placed in this container.
self.container = QWidget()
scroller.setWidget(self.container)
Here's the full sample program I created:
import sys
from PyQt5.QtWidgets import QMainWindow, QWidget, QScrollArea, QVBoxLayout, QLabel, QApplication
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.resize(1100, 800)
scroller = QScrollArea()
scroller.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.container = QWidget()
scroller.setWidget(self.container)
scroller.resize(self.width(),self.height())
scroller.setWidgetResizable(True)
self.setCentralWidget(scroller)
self.holderColumn=QVBoxLayout()
txtList=["apple","banana","orange","triangle","circle","square","moon","star","sun","delta"]
objs=list()
for i in txtList:
tempLabel=QLabel()
tempLabel.setText(i)
tempLabel.setFixedSize(300,300)
objs.append(tempLabel)
self.holderColumn.addWidget(tempLabel)
self.container.setLayout(self.holderColumn)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

How to apply QScrollerProperties to a QScroller, to get rid of overshoot?

As the title says I'm trying to make a scrollArea that uses QScroller with grabgesture so I can scroll by dragging on the widget. I found some good examples and got it working. Now I want to remove the overshoot that happens when you drag further than there is items in the widget.
But when I try to tweak the Qscroller, I can't seem to figure out how to apply the QScrollerProperties to the QScroller. Which is how I assume you remove the overshoot.
Here is an example of the code:
import sys
from PyQt5.QtWidgets import (
QApplication,
QFormLayout,
QGridLayout,
QLabel,
QScrollArea,
QScroller,
QScrollerProperties,
QWidget,
)
class MainWindow(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
scroll_area = QScrollArea()
layout = QGridLayout(self)
layout.addWidget(scroll_area)
scroll_widget = QWidget()
scroll_layout = QFormLayout(scroll_widget)
for i in range(200):
scroll_layout.addRow(QLabel('Label #{}'.format(i)))
scroll_area.setWidget(scroll_widget)
scroll = QScroller.scroller(scroll_area.viewport())
scroll.grabGesture(scroll_area.viewport(), QScroller.LeftMouseButtonGesture)
scroll.scrollerPropertiesChanged.connect(self.PropsChanged) #Just to see if I could registre a change
props = scroll.scrollerProperties()
props.setScrollMetric(QScrollerProperties.VerticalOvershootPolicy,QScrollerProperties.OvershootAlwaysOff)
props.setScrollMetric(QScrollerProperties.DragStartDistance, 0.01)
#Apply Qscroller properties here somehow?
print(scroll.scrollerProperties().scrollMetric(QScrollerProperties.DragStartDistance))
scroll.scrollerProperties = props #Maybe? Doesn't seem to change the overshoot?
def PropsChanged(self):
print("Something is being changed??")
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
I'm not sure how to proceed from here.
Any help would be appriciated :)
Just call scroll.setScrollerProperties(props) once you've set the new properties.
When you call scrollerProperties() you get "copy" of the current properties: it is not a pointer to the actual properties, so nothing changes unless you apply them back to the scroller.
It's almost like calling self.font():
font = self.font()
font.setPointSize(20)
# at this point, the widget font is still the same...
# unless you do this:
self.setFont(font)
The same applies to almost any property, like text()/setText() for labels, palette()/setPalette(), etc.
To prevent the vertical overshoot, you have to use setScrollMetric with VerticalOvershootPolicy, and set the value to OvershootAlwaysOff:
props.setScrollMetric(QScrollerProperties.VerticalOvershootPolicy,
QScrollerProperties.OvershootAlwaysOff)
scroll.setScrollerProperties(props)

Overriding QLabel widget in PyQT

I am new to PyQt perhaps thats why facing this issue. I am trying to make a component inserter for excel sheets. For this purpose I am using QT for interface and using Qlabels within parent class of QMainWindow. On the basis of item selected from Qlist Widget, few Qlabels have to change on mainwindow dynamically Component inserter
As can be seen in above picture, the labels like WCAP-; Part Number and all below needs to change dynamically when the selected items change(when select button is clicked). But what happening is if I choose a different item from list, the previous Label stays and the new label is overlapping it as can be seen from picture below showing overlapping of labels
The code below shows that whenever button "Select" is pressed", label2 (Qlabel2) is formed, how can i delete the previous label whenever select button is pressed so that new Label dynamically replaces the old label.
Thanks a lot in advance.
def Display(self):
self.close()
label1 = QtGui.QLabel("Select the sheet",self)
label1.move(0,15)
self.listwidget = QtGui.QListWidget(self)
self.listwidget.move(0,40)
self.listwidget.resize(150,150)
for i in range(len(self.sheetnames)):
self.listwidget.addItem("%s"%self.sheetnames[i])
btn = QtGui.QPushButton('Select',self)
btn.resize(50,50)
btn.move(170,40)
btn.clicked.connect(self.Selected)
self.show()
def Selected(self):
self.close()
selecteditem = self.listwidget.currentItem().text()
self.sheetindex = self.sheetnames.index(selecteditem)
print self.sheetindex
aa = self.loadsheet.sheet_by_name(selecteditem)
global label2
label2 = QtGui.QLabel("",self)
label2.setText(selecteditem)
label2.move(0,190)
self.show()
self.InputParameters(aa)
You see a new QLabel because you create a new one every time you call Selected. I would initiate the UI at the creation of the widget (in the __init__ method):
def __init__(self):
self.label2 = QtGui.QLabel("",self)
And only update the text of the Qlabel when Selected is executed:
def Selected(self):
self.label2.setText(selecteditem)
About reinitializing all labels with an unknown number of labels and removing the old ones, you might want to look at QLabel.setParent(None). I wrote you a little example:
from PyQt4 import QtGui, QtCore
import sys
class test(QtGui.QWidget):
def __init__(self,parent=None):
self.widget=QtGui.QWidget.__init__(self, parent)
# Button to add labels
self.btnAdd = QtGui.QPushButton('Add')
self.btnAdd.connect(self.btnAdd, QtCore.SIGNAL('clicked()'),self.btnAddPressed)
# Button to remove labels
self.btnRemove = QtGui.QPushButton('Remove')
self.btnRemove.connect(self.btnRemove, QtCore.SIGNAL('clicked()'), self.btnRemovePressed)
# List to keep track of labels
self.labels=[]
# Layout
self.hbox = QtGui.QHBoxLayout()
self.hbox.addWidget(self.btnAdd)
self.hbox.addWidget(self.btnRemove)
self.setLayout(self.hbox)
self.show()
def btnAddPressed(self):
"""Adds a new label."""
self.labels.append(QtGui.QLabel("lbl"+str(len(self.labels)+1), self))
self.hbox.addWidget(self.labels[-1])
def btnRemovePressed(self):
"""Removes last label."""
self.labels[-1].setParent(None)
self.labels.pop(-1)
def main():
#Creating application
app = QtGui.QApplication(sys.argv)
main_win = test()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

How to interactively add widgets using QAction in Pyside/Pyqt without using layout management?

I'm trying to make a tool window for Maya, in which I can right-click anywhere, and if I click 'add', a rectangle widget shows up at my cursor position.
Now my right-click functionality works. I can also get my cursor position in addPicker() function. But I am having problem with placing newly-created widgets. If I add a layout and add the newly-created widgets to it, they actually show up. However, if I didn't create a layout for those widgets, no matter what position I tested, nothing shows up in my window.
Hopefully someone has some ideas. Thank you all in advance.
A right-click screenshot:
class RightClickMenu(QtGui.QMenu):
def __init__(self, *args, **kwargs):
super(RightClickMenu, self).__init__(*args)
self.parentWidget().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.parentWidget().customContextMenuRequested.connect(self.menuPos)
def menuPos(self, *args):
self.exec_(QtGui.QCursor.pos())
class Ui_window(object):
def setupUi(self, window):
window.setObjectName("window")
window.resize(555, 900)
self.widget_base = QtGui.QWidget()
self.verticalLayout_window = QtGui.QVBoxLayout(window)
self.verticalLayout_window.addWidget(self.widget_base)
self.menu_popup = RightClickMenu(self.widget_base)
self.menu_popup.setObjectName("popupMenu")
self.verticalLayout_widget = QtGui.QVBoxLayout(self.widget_base)
# Action - add picker
addAction = QtGui.QAction('Add Picker', self.widget_base)
addAction.setShortcut('Ctrl+A')
addAction.setStatusTip('Add Picker')
addAction.triggered.connect(self.addPicker)
self.menu_popup.addAction(addAction)
# Action - delete picker
deleteAction = QtGui.QAction('Delete Picker', self.widget_base)
deleteAction.setShortcut('Ctrl+D')
deleteAction.setStatusTip('Delete Picker')
deleteAction.triggered.connect(self.deletePicker)
self.menu_popup.addAction(deleteAction)
def addPicker(self):
cursorPos = QtGui.QCursor.pos()
localPos = self.widget_base.mapFromGlobal(cursorPos)
######################################################################
# how??? below doesn't work.
self.pushButton = QtGui.QPushButton(self.widget_base)
self.pushButton.setGeometry(QtCore.QRect(220, 50, 75, 23))
self.pushButton.setObjectName("pushButton")
def deletePicker(self):
print 'delete'
def run():
import sys
try:
Ui_window.close()
except:
pass
pickerWindow = QtGui.QDialog()
ui = Ui_window()
ui.setupUi(pickerWindow)
pickerWindow.show()
pickerWindow.exec_()
Surprising solution (see this question):
self.pushButton.show()

Qt formlayout not expanding qplaintextedit vertically

I'm confused why a QPlainTextEdit widget will not resize vertically when added to a QFormLayout. In the code below the text field correctly scales up horizontally, but does not scale up vertically.
Can anyone explain this behavior and offer a solution? I've tried all the tricks I know to no avail.
from PyQt4 import QtGui
class Diag(QtGui.QDialog):
def __init__(self, parent, *args, **kwargs):
QtGui.QDialog.__init__(self, parent)
layout = QtGui.QFormLayout(self)
widg = QtGui.QPlainTextEdit(self)
layout.addRow('Entry', widg)
if __name__ == '__main__': #pragma: no cover
app = QtGui.QApplication([])
window = Diag(None)
window.show()
app.exec_()
Here is an example of the QPlainTextEdit widget not resizing vertically:
This is on Windows 7 using PyQt 4.5.2 and Python 32-bit 2.6.
Thanks.
It seems that, by default, a QFormLayout will only resize the height of its fields according to their sizeHint.
To change this behaviour, adjust the vertical stretch as appropriate:
policy = widg.sizePolicy()
policy.setVerticalStretch(1)
widg.setSizePolicy(policy)
You should set the object in the last row of formlayout (see QPlainTextEdit), its vertical Stretch factor should not be 0.
This works for me:
it is small at the time of calculating the initial size of the dialog widget and can grow with the dialog once it is already visible
class q2text(QTextEdit):
def showEvent(self, ev):
self.updateGeometry()
return super().showEvent(ev)
def sizeHint(self):
if self.isVisible():
return QSize(99999, 99999)
else:
return super().sizeHint()

Resources