First, I started using PyQt few hours ago.
So far so good - im writing rss client to familiarize myself with PyQt
I got QApplication, QMainWindow and two custom widgets.
First custom widget is:
class RssItem(QWidget):
__pyqtSignals__ = ("articleViewed(bool)",
"articleOpened(bool)",
"articleMarkedGood(bool)")
def __init__(self, title, date, parent = None):
super(RssItem, self).__init__(parent)
self.initWidget(title, date)
def initWidget(self, title, date):
title = QLabel(title)
date = QLabel(date)
titleBox = QHBoxLayout()
titleBox.addWidget(title)
titleBox.addWidget(date)
self.setLayout(titleBox)
That displays (for now) title and date in single row
Second one accepts array of RssItem widgets and display them in vertical list:
class ItemsList(QWidget):
def __init__(self, items, parent=None):
super(ItemsList, self).__init__(parent)
self.initWidget(items)
def initWidget(self, items):
listBox = QVBoxLayout(self)
for item in items:
listBox.addWidget(item)
listBox.addStretch(1)
self.setLayout(listBox)
How do I make this list scrollable?
Keep in mid I'm planing to have multiple ItemList's in one window each should have it's own scrollbar.
Main app function as for now is only for testing these 2 widgets:
class MainApp(Qt.QApplication):
def __init__(self, args):
super(MainApp, self).__init__(args)
self.addWidgets()
self.exec_()
def addWidgets(self):
self.window = MainWindow()
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.statusBar().showMessage("ok")
self.resize(640, 480)
self.setWindowTitle("Smart Rss")
items=[]
for x in range(0, 200):
items.append(RssItem("Title no %s" % x, "2000-1-%s" %x))
self.setCentralWidget(ItemsList(items))
self.show()
EDIT:Getting closer, changed ItemList.initWidget to
def initWidget(self, items):
scroll= QScrollArea(self)
wrap = QWidget(self)
listBox = QVBoxLayout(self)
for item in items:
listBox.addWidget(item)
listBox.addStretch(1)
wrap.setLayout(listBox)
scroll.setWidget(wrap)
But now I cant figure out how to make QScrollArea fill all available space and auto resize when it's changed.
Try scroll.setWidgetResizable(True) like in here:
def initWidget(self, items):
listBox = QVBoxLayout(self)
self.setLayout(listBox)
scroll = QScrollArea(self)
listBox.addWidget(scroll)
scroll.setWidgetResizable(True)
scrollContent = QWidget(scroll)
scrollLayout = QVBoxLayout(scrollContent)
scrollContent.setLayout(scrollLayout)
for item in items:
scrollLayout.addWidget(item)
scroll.setWidget(scrollContent)
Related
I have a Qgroupbox which contains Qcombobox with Qlabels, I want to select a value from Qcombobox and display the value as Qlabel. I have the complete code, even I do print value before and after within function every thing works as it should, Only display setText wont set text to Qlabel and update it.
Current screen
What I want
I've corrected signal code, when Qgroupbox in it Qcombobox appears or value would be changed, self.activation.connect(......) would emit an int of the index. to ensure that would work I print it-value inside the def setdatastrength(self, index), see figure below indeed it works, then argument would be passed to function self.concreteproperty.display_condata(it) would be called and do a print of value inside def display_condata(self, value) to make sure about value passing, as shown figure below, it does work. This line code self.con_strength_value.setText(fmt.format(L_Display))
wont assign value to Qlabel.
The script
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class secondtabmaterial(QtWidgets.QWidget):
def __init__(self, parent=None):
super(secondtabmaterial, self).__init__(parent)
self.concretewidgetinfo = ConcreteStrengthInFo()
Concrete_Group = QtWidgets.QGroupBox(self)
Concrete_Group.setTitle("&Concrete")
Concrete_Group.setLayout(self.concretewidgetinfo.grid)
class ConcreteStrengthComboBox(QtWidgets.QComboBox):
def __init__(self, parent = None):
super(ConcreteStrengthComboBox, self).__init__(parent)
self.addItems(["C12/15","C16/20","C20/25","C25/30","C30/37","C35/45"
,"C40/50","C45/55","C50/60","C55/67","C60/75","C70/85",
"C80/95","C90/105"])
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.compressive_strength = ["12","16","20","25","30","35","40",
"45","50","55","60","70","80","90"]
class ConcreteProperty(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteProperty, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
concretestrength_lay = QtWidgets.QHBoxLayout(self)
fctd = "\nfcd\n\nfctd\n\nEc"
con_strength = QtWidgets.QLabel(fctd)
self.con_strength_value = QtWidgets.QLabel(" ")
concretestrength_lay.addWidget(con_strength)
concretestrength_lay.addWidget(self.con_strength_value, alignment=QtCore.Qt.AlignRight)
self.setLayout(concretestrength_lay)
#QtCore.pyqtSlot(int)
def display_condata(self, value):
try:
L_Display = str(value)
print("-------- After ------")
print(L_Display, type(L_Display))
fmt = "{}mm"
self.con_strength_value.setText(fmt.format(L_Display))
except ValueError:
print("Error")
class ConcreteStrengthInFo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteStrengthInFo, self).__init__(parent)
self.concreteproperty = ConcreteProperty()
self.concretestrengthbox = ConcreteStrengthComboBox()
self.concretestrengthbox.activated.connect(self.setdatastrength)
hbox = QtWidgets.QHBoxLayout()
concrete_strength = QtWidgets.QLabel("Concrete strength: ")
hbox.addWidget(concrete_strength)
hbox.addWidget(self.concretestrengthbox)
self.grid = QtWidgets.QGridLayout()
self.grid.addLayout(hbox, 0, 0)
self.grid.addWidget(self.concreteproperty, 1, 0)
#QtCore.pyqtSlot(int)
def setdatastrength(self, index):
it = self.concretestrengthbox.compressive_strength[index]
self.concreteproperty.display_condata(it)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = secondtabmaterial()
w.show()
sys.exit(app.exec_())
Above code is corrected and final. Now it works as it should.
I think the issue is that your receiving slot doesn't match any of the available .activated signals.
self.activated.connect(self.setdatastrength)
#QtCore.pyqtSlot()
def setdatastrength(self):
index = self.currentIndex()
it = self.compressive_strength[index]
print(it)
self.concreteproperty.display_condata(it)
The QComboBox.activated signal emits either an int of the index, or a str of the selected value. See documentation.
You've attached it to setdatastrength which accepts doesn't accept any parameters (aside from self, from the object) — this means it doesn't match the signature of either available signal, and won't be called. If you update the definition to add the index value, and accept a single int it should work.
self.activated.connect(self.setdatastrength)
#QtCore.pyqtSlot(int) # add the target type for this slot.
def setdatastrength(self, index):
it = self.compressive_strength[index]
print(it)
self.concreteproperty.display_condata(it)
After the update — the above looks now to be fixed, although you don't need the additional index = self.currentIndex() in setdatastrength it's not doing any harm.
Looking at your code, I think the label is being updated. The issue actually is that you can't see the label at all. Looking at the init for ConcreteProperty
class ConcreteProperty(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteProperty, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.concretestrength_lay = QtWidgets.QHBoxLayout()
fctd = "\nfcd\n\nfctd\n\nEc"
con_strength = QtWidgets.QLabel(fctd)
self.con_strength_value = QtWidgets.QLabel(" ")
self.concretestrength_lay.addWidget(con_strength)
self.concretestrength_lay.addWidget(self.con_strength_value, alignment=QtCore.Qt.AlignLeft)
The reason the changes are not appearing is that you create two ConcreteProperty objects, one in ConcreteStrengthInfo and one in ConcreteStrengthComboBox. Updates to the combo box trigger an update of the ConcreteProperty attached to the combobox, not the other one (they are separate objects). The visible ConcreteProperty is unaffected.
To make this work, you need to move the signal attachment + the slot out of the combo box object. The following is a replacement for the two parts —
class ConcreteStrengthComboBox(QtWidgets.QComboBox):
def __init__(self, parent = None):
super(ConcreteStrengthComboBox, self).__init__(parent)
self.addItems(["C12/15","C16/20","C20/25","C25/30","C30/37","C35/45","C40/50","C45/55",
"C50/60","C55/67","C60/75","C70/85","C80/95","C90/105"])
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.compressive_strength = ["12","16","20","25","30","35","40","45","50","55",
"60","70","80","90"]
class ConcreteStrengthInFo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ConcreteStrengthInFo, self).__init__(parent)
hbox = QtWidgets.QHBoxLayout()
concrete_strength = QtWidgets.QLabel("Concrete strength: ")
hbox.addWidget(concrete_strength)
self.concreteproperty = ConcreteProperty()
self.concretestrengthbox = ConcreteStrengthComboBox()
hbox.addWidget(self.concretestrengthbox)
self.concretestrengthbox.activated.connect(self.setdatastrength)
self.vlay = QtWidgets.QVBoxLayout()
self.vlay.addLayout(hbox)
self.vlay.addLayout(self.concreteproperty.concretestrength_lay)
#QtCore.pyqtSlot(int)
def setdatastrength(self, index):
it = self.concretestrengthbox.compressive_strength[index]
print(it)
self.concreteproperty.display_condata(it)
This works for me locally.
I want to add images to cells but it cant show properly,can you please tell me how to increase the row height and column width of the table widget.
Here given bellow is my code:
from PyQt4 import QtGui
import sys
imagePath = "pr.png"
class ImgWidget1(QtGui.QLabel):
def __init__(self, parent=None):
super(ImgWidget1, self).__init__(parent)
pic = QtGui.QPixmap(imagePath)
self.setPixmap(pic)
class ImgWidget2(QtGui.QWidget):
def __init__(self, parent=None):
super(ImgWidget2, self).__init__(parent)
self.pic = QtGui.QPixmap(imagePath)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(0, 0, self.pic)
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
tableWidget = QtGui.QTableWidget(10, 2, self)
# tableWidget.horizontalHeader().setStretchLastSection(True)
tableWidget.resizeColumnsToContents()
# tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# tableWidget.setFixedWidth(tableWidget.columnWidth(0) + tableWidget.columnWidth(1))
tableWidget.resize(400,600)
tableWidget.setCellWidget(0, 1, ImgWidget1(self))
tableWidget.setCellWidget(1, 1, ImgWidget2(self))
if __name__ == "__main__":
app = QtGui.QApplication([])
wnd = Widget()
wnd.show()
sys.exit(app.exec_())
When using widgets inside the QTableWidget are not really the content of the table, they are placed on top of it, so resizeColumnsToContents() makes the size of the cells very small since it does not take into account the size of those widgets, resizeColumnsToContents() takes into account the content generated by the QTableWidgetItem.
On the other hand if you want to set the height and width of the cells you must use the headers, in the following example the default size is set using setDefaultSectionSize():
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
tableWidget = QtGui.QTableWidget(10, 2)
vh = tableWidget.verticalHeader()
vh.setDefaultSectionSize(100)
# vh.setResizeMode(QtGui.QHeaderView.Fixed)
hh = tableWidget.horizontalHeader()
hh.setDefaultSectionSize(100)
# hh.setResizeMode(QtGui.QHeaderView.Fixed)
tableWidget.setCellWidget(0, 1, ImgWidget1())
tableWidget.setCellWidget(1, 1, ImgWidget2())
lay = QtGui.QVBoxLayout(self)
lay.addWidget(tableWidget)
If you want the size can not be varied by the user then uncomment the lines.
I'm having issues getting items with custom widgets to show up in a list widget. The items show up blank in the example below...
from PySide2 import QtWidgets
class ItemWidget(QtWidgets.QWidget):
def __init__(self,parent = None):
super(ItemWidget, self).__init__(parent)
layout = QtWidgets.QHBoxLayout()
self.setLayout(layout)
self.checkBox = QtWidgets.QCheckBox()
self.label = QtWidgets.QLabel('test')
layout.addWidget(self.checkBox)
layout.addWidget(self.label)
class ListWidget(QtWidgets.QListWidget):
def __init__(self,parent = None):
super(ListWidget,self).__init__(parent)
self.initUI()
def initUI(self):
for i in range(10):
item = QtWidgets.QListWidgetItem()
self.addItem(item)
widget = ItemWidget(self)
self.setItemWidget(item,widget)
self.show()
lister = ListWidget()
It looks like QlistWidget won't do what you want, so you'll need to approach it from a lower level.
PySide.QtGui.QListWidget.setItemWidget(item, widget)
This function should only be used to display static content in the place of a list widget item. If you want to display custom dynamic content or implement a custom editor widget, use PySide.QtGui.QListView and subclass PySide.QtGui.QItemDelegate instead.
How can I add customized items to a QListWidget with a background color that I choose, and add a bottom border to each item, like this draft example in the picture below.
This is the code that I wrote:
from PyQt5 import QtWidgets, QtGui
import sys
class CustomListHead(QtWidgets.QWidget):
def __init__(self):
super(CustomListHead, self).__init__()
self.project_title = QtWidgets.QLabel("Today")
self.set_ui()
def set_ui(self):
grid_box = QtWidgets.QGridLayout()
grid_box.addWidget(self.project_title, 0, 0)
self.setLayout(grid_box)
self.show()
class CustomListItem(QtWidgets.QWidget):
def __init__(self):
super(CustomListItem, self).__init__()
self.project_title = QtWidgets.QLabel("Learn Python")
self.task_title = QtWidgets.QLabel("Learn more about forms, models and include")
self.set_ui()
def set_ui(self):
grid_box = QtWidgets.QGridLayout()
grid_box.addWidget(self.project_title, 0, 0)
grid_box.addWidget(self.task_title, 1, 0)
self.setLayout(grid_box)
self.show()
class MainWindowUI(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindowUI, self).__init__()
self.list_widget = QtWidgets.QListWidget()
self.set_ui()
def set_ui(self):
custom_head_item = CustomListHead()
item = QtWidgets.QListWidgetItem(self.list_widget)
item.setSizeHint(custom_head_item.sizeHint())
self.list_widget.setItemWidget(item, custom_head_item)
self.list_widget.addItem(item)
custom_item = CustomListItem()
item = QtWidgets.QListWidgetItem(self.list_widget)
item.setSizeHint(custom_item.sizeHint())
self.list_widget.addItem(item)
self.list_widget.setItemWidget(item, custom_item)
vertical_layout = QtWidgets.QVBoxLayout()
vertical_layout.addWidget(self.list_widget)
widget = QtWidgets.QWidget()
widget.setLayout(vertical_layout)
self.setCentralWidget(widget)
self.show()
app = QtWidgets.QApplication(sys.argv)
ui = MainWindowUI()
sys.exit(app.exec_())
I see you have QListWidgetItem with you.
From documentation you can customize each widget item, customize it and add to your listwidget:
The appearance of the text can be customized with setFont(), setForeground(), and setBackground(). Text in list items can be aligned using the setTextAlignment() function. Tooltips, status tips and "What's This?" help can be added to list items with setToolTip(), setStatusTip(), an
d setWhatsThis().
http://doc.qt.io/qt-5/qlistwidgetitem.html#details
I need to create multi-window GUI, first I tried it with QWidgets, but finally I discover QStackWidget tool I need to use. So Im trying to, but Ive got some problems. Thanks for Your time.
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.mainWidget = MainWidget()
self.searchWidget = SearchWidget()
self.sWidget = QStackedWidget()
self.sWidget.addWidget(self.mainWidget)
self.sWidget.addWidget(self.searchWidget)
self.initUI()
and calling setCurrentWidget from the sub_widget class:
class MainWidget(QWidget):
def __init__(self, parent=MainWindow):
super(MainWidget,self).__init__()
self.initUI()
def initUI(self):
searchButton = QPushButton('searchButton',self)
optionButton = QPushButton('optionButton',self)
quitButton = QPushButton('quitButton',self)
listButton = QPushButton('listButton',self)
searchButton.clicked.connect(self.goSearch)
hbox = QHBoxLayout()
hbox.addWidget(listButton)
hbox.addWidget(quitButton)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addWidget(searchButton)
vbox.addWidget(optionButton)
vbox.addLayout(hbox)
self.setLayout(vbox)
def goSearch(self):
self.parent().sWidget.setCurrentWidget(self.parent().searchWidget)
Ive got this message from IDE:
self.parent().sWidget.setCurrentWidget(self.parent().searchWidget)
AttributeError: 'PySide.QtGui.QStackedWidget' object has no attribute 'sWidget'
What is the thing Im doing wrong?
I'm going to comment on the code you posted here: http://pastebin.com/fBfS1X5m
An important thing to know is that you can put widgets within widgets and so on. For example:
class Widget(QWidget):
def __init__(self, parent=None):
layout = QVBoxLayout(self)
childWidget = QWidget(parent=self)
layout.addWidget(childWidget)
Just a quick note: You don't need setLayout if you pass self to the main layout constructor - via the docs.
Anyways, what I'm trying to illustrate here is that the QStackedWidget and the SearchWidget really shouldn't be a part of the MainWindow, but should live inside their own relevant widget that will handle switching between the QStackedWidget pages.
For example the MainWindow.__init__ would only look like this:
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.mainWidget = MainWidget(self)
self.setCentralWidget(self.mainWidget)
self.initUI()
Your MainWidget would then look something like:
class MainWidget(QtGui.QWidget):
...
def initUI(self):
...
self.stack = QtGui.QStackedWidget(parent=self)
self.searchWidget = SearchWidget(parent=self)
self.searchWidget.searchButton.clicked.connect(self.goSearch)
self.backWidget = BackWidget(parent=self)
self.backWidget.backButton.clicked.connect(self.goBack)
...
def goSearch(self):
self.stack.setCurrentWidget(self.backWidget)
def goBack(self):
self.stack.setCurrentWidget(self.searchWidget)
I've renamed some of the class names to make a little more sense (To me at least). SearchWidget was your old MainWidget. BackWidget was your old SearchWidget. Following those changes SearchWidget would look the same as your old MainWidget with one exception - we save a reference to the search button so we can access it in the MainWidget class as seen above (when we connect their signals to our slots). We do the same for the button in BackWidget.
The two renamed "child" widgets:
class SearchWidget(QtGui.QWidget):
...
def initUI(self):
self.searchButton = QtGui.QPushButton('searchButton', parent=self)
optionButton = QtGui.QPushButton('optionButton', parent=self)
quitButton = QtGui.QPushButton('quitButton', parent=self)
listButton = QtGui.QPushButton('listButton', parent=self)
vbox = QtGui.QVBoxLayout(self)
vbox.addStretch(1)
vbox.addWidget(self.searchButton)
vbox.addWidget(optionButton)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(listButton)
hbox.addWidget(quitButton)
vbox.addLayout(hbox)
class BackWidget(QtGui.QWidget):
...
def initUI(self):
self.backButton = QtGui.QPushButton('GoBack', parent=self)
So now we have something like:
MainWindow
|---MainWidget
|---QStackedWidget
|---SearchWidget
|---BackWidget
You can find the full working code here.
This line:
def __init__(self, parent=MainWindow):
sets the MainWindow class as a default argument, when you actually need an instance. But even if it was an instance, in the next line, you also fail to pass it on to the base-class:
super(MainWidget,self).__init__()
What you need to do instead is something like this:
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
# pass an instance of MainWindow here
self.mainWidget = MainWidget(self)
...
class MainWidget(QWidget):
def __init__(self, parent):
# pass the parent to the base-class
super(MainWidget, self).__init__(parent)
...
UPDATE:
The stack-widget will re-parent any widgets added to it, so that it becomes the parent. There are ways of working around this, but I think the real problem with your code is that you have the structure backwards. The buttons that set the current widget should be controlled by the main-window, and the widgets in the stack should work completely independantly of that.