Kivy Scrollview in kv language - id not defined - scrollview

Trying to figure out how to implement a straight-forward ScrollView in KV language based on the examples given in the documentation. I cannot believe I cannot find a single example of this (only parts of solution), so I thought it would be easy. Turns out it's not.
My issue is that I need to populate my scrollable grid layout with a list of labels from within the kivy script, using add_widget. That's because I have a variable number of of labels to add (although that number is fixed in the below example to make things simple). However the program wouldn't let me do it, saying that the ID I defined for the grid layout object is not defined. Therefore I am not able to add the labels to the grid layout.
NameError: name '_gridlayout' is not defined
Any help appreciated. Thanks
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
Builder.load_string('''
<MainScreen>:
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
size_hint: 1, .2
Label:
text: "Random text"
AnchorLayout:
anchor_x: 'center'
anchor_y: 'bottom'
size_hint: 1, .8
ScrollView:
GridLayout:
id: _gridlayout
cols: 1
padding: 10
spacing: 10
size_hint_y: None
width: 500
''')
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
self.buildList()
super(MainScreen, self).__init__(**kwargs)
def buildList(self):
for i in range(30):
btn = Label(text=str(i), size_hint_y=None, height=40)
_gridlayout.add_widget(btn) # <- ERROR
class SMApp(App):
def build(self):
return MainScreen()
if __name__ == '__main__':
SMApp().run()
UPDATE: Corrected script below.
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
Builder.load_string('''
<MainScreen>:
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
size_hint: 1, .2
Label:
text: "Random text"
AnchorLayout:
anchor_x: 'center'
anchor_y: 'bottom'
size_hint: 1, .8
ScrollView:
GridLayout:
id: _gridlayout
cols: 1
padding: 10
spacing: 10
size_hint_y: None
width: 500
''')
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.buildList()
def buildList(self):
for i in range(30):
btn = Label(text=str(i), size_hint_y=None, height=40)
self.ids._gridlayout.add_widget(btn)
self.ids._gridlayout.bind(minimum_height=self.ids._gridlayout.setter('height'))
class SMApp(App):
def build(self):
return MainScreen()
if __name__ == '__main__':
SMApp().run()

Kivy is very picky about calling Widget.__init__() first. So if you overwrite __init__ of a widget be sure to first call super().__init__, otherwise you can get errors like you encountered or "random" crashes.
To fix change
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
self.buildList()
super(MainScreen, self).__init__(**kwargs)
to
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.buildList()

Related

I would like to rotate a widget using QGraphicsScene in PyQt (QLineEdit and QPushButton)

I would like to rotate a widget in pyqt5, I have developed this code but it doesn't work. The angle doesn't update and it returns a False. Do anyone know how to update this angle to make the widget rotate? If someone can help, thank you.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
robotx=200
roboty=100
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My Awesome Rotating Widget")
self.setGeometry(0, 0, 640, 480)
self.R=Robot()
self.angle=0
self.AngleLineEdit=QLineEdit(self)
self.AngleLineEdit.setGeometry(50,50,160,35)
self.AngleLineEdit.setStyleSheet("background-color: rgba(50,50,50,20); color:black; font-weight: bold; font-size: 8pt; font-family: Helvetica; border-radius:5px;")
self.AcceptButton=QPushButton(self)
self.AcceptButton.setText("Accept")
self.AcceptButton.setGeometry(50,100,160,35)
self.AcceptButton.setStyleSheet("QPushButton{color:black; font-weight: bold; font-size: 8pt; font-family: Helvetica; background-color:rgb(255,255,255,20); border-radius:5px}""QPushButton:hover{background-color : rgb(255,255,255,100);}")
container = RotatableContainer(self,self.R, 0)
container.move(robotx,roboty)
container.resize(150,150)
container.setStyleSheet("background-color:transparent;")
self.AcceptButton.clicked.connect(lambda: self.RotateWidget())
self.AcceptButton.clicked.connect(container.rotate)
self.show()
def RotateWidget(self):
self.angle=int(self.AngleLineEdit.text())
print(self.angle)
class RotatableContainer(QGraphicsView):
def __init__(self, parent, widget, angle):
super().__init__(parent)
scene = QGraphicsScene(self)
self.setScene(scene)
self.proxy = QGraphicsProxyWidget()
self.proxy.setWidget(widget)
self.proxy.setTransformOriginPoint(self.proxy.boundingRect().center())
self.proxy.setRotation(angle)
scene.addItem(self.proxy)
def rotate(self, angle):
print(angle)
self.proxy.setRotation(angle)
class Robot(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0,0,100,100)
def paintEvent(self, event):
p=QPainter(self)
r=QRect(0,0,99,99)
c=QColor(0,0,0)
p.setBrush(QBrush(c))
p.drawRect(r)
app = QApplication([])
window = MainWindow()
app.exec_()
I have seen an example of how to rotate a widget using a qslider but I don't know how to adapt it using a QLineEdit and a QPushButton.
The first argument of clicked is always its check state, which by default is False for non checkable/checked buttons.
Since you've connected the signal to the rotate function, the argument is that of the button signal, and since False also means 0, you're practically doing self.proxy.setRotation(0).
Set the container as an instance attribute and call its rotate function from there:
class MainWindow(QMainWindow):
def __init__(self):
# ...
self.container = RotatableContainer(self,self.R, 0)
self.container.move(robotx,roboty)
self.container.resize(150,150)
self.container.setStyleSheet("background-color:transparent;")
self.AcceptButton.clicked.connect(self.RotateWidget)
self.show()
def RotateWidget(self):
angle = self.AngleLineEdit.text()
if angle.isdigit():
self.angle = angle
self.container.rotate(self.angle)
Note: you should always use layout managers, and only classes and constants should have capitalized names (see the Style Guide for Python Code).

How to stretch QLabel in PyQt5

How to change the following code to get the QLabel stretch to width of the window ?
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 200, 100)
self.label = QLabel('Hello World!', self)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet('font-size: 12pt; background-color: red')
self.show()
app = QApplication([])
win = Window()
app.exec()
As the documentation about QMainWindow says, you must set a central widget for it:
Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder.
The problem is that you need a layout manager in order to properly adapt widget sizes inside a parent, and just manually setting widget geometries is generally discouraged.
You created the label as a direct child, so it will have no knowledge about its parents size changes.
Just set the label as central widget.
self.setCentralWidget(self.label)
Otherwise, you can use a container widget, set a layout and add the label to it, but you still must set the central widget.
central = QWidget()
layout = QVBoxLayout(central)
layout.addWidget(self.label)
self.setCentralWidget(central)
The alternative is to directly use a QWidget instead of QMainWindow as you did in your answer.
you can use sizePolicy
self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
Thank you very much for your answers. The problem is now solved by the following code changes
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Window(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 200, 100)
self.label = QLabel('Hello World!', self)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet('font-size: 12pt; background-color: red')
self.box_layout = QHBoxLayout()
self.box_layout.addWidget(self.label)
self.setLayout(self.box_layout)
self.show()
app = QApplication([])
win = Window()
app.exec()
Edit: laytout -> box_layout

Problem with changing the value of main button in KivyMD Menu

I have created a KivyMD Menu. When I click on the main Button, the menu is opening without a problem. However when I click on a menu button the value of the main button is not changing. Nothing happens. I thought the code is sufficient to achieve it. Does anyone know a solution? Thank you in advance!
py file:
from kivy.core.window import Window
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.menu import MDDropdownMenu
Window.size = (400, 800)
class homescreen(Screen):
pass
GUI = Builder.load_file("main.kv")
class MainApp(MDApp, homescreen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.homescreen = Builder.load_string("homescreen")
menu_items = [{"icon": "git", "text": f"Item {i}"} for i in range(5)]
self.menu = MDDropdownMenu(
caller=self.ids.drop_item,
items=menu_items,
#position="center",
width_mult=4,
)
self.menu.bind(on_release=self.set_item)
def set_item(self, instance_menu, instance_menu_item):
self.ids.drop_item.set_item(instance_menu_item.text)
self.menu.dismiss()
def build(self):
return self.homescreen
if __name__ == "__main__":
MainApp().run()
main.kv:
<homescreen>:
MDDropDownItem:
id: drop_item
pos_hint: {'center_x': .5, 'center_y': .5}
text: "Select"
on_release: app.menu.open()
Here is your improved code
py file:
from kivy.core.window import Window
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.menu import MDDropdownMenu
Window.size = (400, 800)
class homescreen(Screen):
pass
GUI = Builder.load_file("main.kv")
class MainApp(homescreen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.homescreen = Builder.load_string("homescreen")
menu_items = [{"icon": "git", "text": f"Item {i}"} for i in range(5)]
self.menu = MDDropdownMenu(
caller=self.ids.drop_item,
items=menu_items,
callback=self.set_item,
width_mult=4,
)
def set_item(self, instance_menu_item):
self.ids.drop_item.text = instance_menu_item.text
self.menu.dismiss()
def build(self):
return self.homescreen
class app(MDApp):
def build(self):
return MainApp()
if __name__ == "__main__":
app().run()
main.ky
<homescreen>:
MDDropDownItem:
id: drop_item
pos_hint: {'center_x': .5, 'center_y': .5}
text: "Select"
on_release: root.menu.open()

KIVY python - scroll view in a layout

I have a simple app in which i would like to insert a scroll view of several buttons.
So there is the base code, i want a scroll view inside the grid layout.
PS: i have this error: Menu object has no attribute 'view'
what I would like to obtain:
debug.py:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.button import Button
class AppScreenManager(ScreenManager):
def __init__(self, **kwargs):
super(AppScreenManager, self).__init__(**kwargs)
class Menu(Screen):
def __init__(self, **kwargs):
super(Menu, self).__init__(**kwargs)
base = ["element {}".format(i) for i in range(40)]
for element in base:
self.view.add_widget(Button(text=element, size=(40,40), size_hint=(1, None), background_color=(0.5, 0.5, 0.5, 1), color=(1,1,1,1)))
Builder.load_file("debug.kv")
class MyAppli(App):
def build(self):
return AppScreenManager()
if __name__ == '__main__':
MyAppli().run()
debug.kv:
#:kivy 1.9.1
<AppScreenManager>:
Menu:
<Menu>:
BoxLayout:
orientation: 'vertical'
BoxLayout:
size: (64, 64)
size_hint: (1, None)
Button:
text: "Menu"
color: (1,1,1,1)
background_color: (.3, .3, .3, 1)
GridLayout: # here i want a scrollview
id: view
cols: 1
Kivy Language
Note that the outermost widget applies the kv rules to all its inner
widgets before any other rules are applied. This means if an inner
widget contains ids, these ids may not be available during the inner
widget’s init function.
ScrollView » Managing the Content Size and Position
By default, the size_hint is (1, 1), so the content size will fit your ScrollView exactly (you will have nothing to scroll). You must deactivate at least one of the size_hint instructions (x or y) of the child to enable scrolling. Setting size_hint_min to not be None will also enable scrolling for that dimension when the ScrollView is smaller than the minimum size.
To scroll a GridLayout on it’s Y-axis/vertically, set the child’s
width to that of the ScrollView (size_hint_x=1), and set the
size_hint_y property to None:
Use Clock.schedule_once to invoke a new method, create_scrollview. Make sure the height is such that there is something to scroll layout.bind(minimum_height=layout.setter('height')). Please refer to the example below for details.
Example
debug.py
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.properties import ObjectProperty
from kivy.clock import Clock
class AppScreenManager(ScreenManager):
def __init__(self, **kwargs):
super(AppScreenManager, self).__init__(**kwargs)
class Menu(Screen):
view = ObjectProperty(None)
def __init__(self, **kwargs):
super(Menu, self).__init__(**kwargs)
Clock.schedule_once(self.create_scrollview)
def create_scrollview(self, dt):
base = ["element {}".format(i) for i in range(40)]
layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter("height"))
for element in base:
layout.add_widget(Button(text=element, size=(50, 50), size_hint=(1, None),
background_color=(0.5, 0.5, 0.5, 1), color=(1, 1, 1, 1)))
scrollview = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))
scrollview.add_widget(layout)
self.view.add_widget(scrollview)
Builder.load_file("debug.kv")
class MyAppli(App):
def build(self):
return AppScreenManager()
if __name__ == '__main__':
MyAppli().run()
debug.kv
#:kivy 1.10.0
<AppScreenManager>:
Menu:
<Menu>:
view: view
BoxLayout:
orientation: 'vertical'
BoxLayout:
size: (64, 64)
size_hint: (1, None)
Button:
text: "Menu"
color: (1, 1, 1, 1)
background_color: (.3, .3, .3, 1)
ScrollView:
id: view
Output
ScrollView:
size: self.size
GridLayout: # here i want a scrollview
id: view
cols: 1
size_hint_y: None
height: self.minimum_height
Button:
text:
size_hint_y: None
Do something like this and add the buttons needed in the gridlayout... I'm new to Kivy so please bear with me.

Why does ConfigParserProperty only work for Widgets created with kv in examples below

The following code works as I expect. When I enter a Number in TextInput and press RETURN, the number is shown in all 3 Labels.
#!/usr/bin/python
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ConfigParserProperty
Builder.load_string("""
<MyBoxLayout>
TextInput:
text: "insert Number <RETURN>"
multiline: False
on_text_validate: root.numberprop=self.text
Label:
text: str(root.numberprop)
Label:
text: str(root.numberprop)
Label:
text: str(root.numberprop)
""")
class MyBoxLayout(BoxLayout):
numberprop= ConfigParserProperty(3, 'one', 'two', 'app',
val_type=int, errorvalue=41)
class TstApp(App):
def build_config(self, config):
config.setdefaults('one', {'two' : '70'})
def build(self, **kw):
return MyBoxLayout()
if __name__ == '__main__':
TstApp().run()
The following code does not work as I expect. When I enter a number in Textinput and press RETURN, only the last Label shows the number.
#!/usr/bin/python
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.properties import ConfigParserProperty
def MyConfigParserProperty():
return ConfigParserProperty(3, 'one', 'two', 'app',
val_type=int, errorvalue=41)
Builder.load_string("""
<MyBoxLayout>
TextInput:
text: "insert Number <RETURN>"
multiline: False
on_text_validate: root.numberprop=self.text
<MyLabel>
text: str(root.numberprop)
""")
class MyLabel(Label):
numberprop=MyConfigParserProperty()
class MyBoxLayout(BoxLayout):
numberprop=MyConfigParserProperty()
def __init__(self, **kw):
super(MyBoxLayout, self).__init__(**kw)
for i in range(3):
self.add_widget(MyLabel())
class TstApp(App):
def build_config(self, config):
config.setdefaults('one', {'two' : '70'})
def build(self, **kw):
return MyBoxLayout()
if __name__ == '__main__':
TstApp().run()
I need a way to create Labels dynamically. How can I do it ?
The following code solves the problem.
#!/usr/bin/python
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.properties import ConfigParserProperty
Builder.load_string("""
<MyBoxLayout>
TextInput:
text: "insert Number <RETURN>"
multiline: False
on_text_validate: app.numberprop=self.text
<MyLabel>
text: str(app.numberprop)
""")
class MyLabel(Label):
pass
class MyBoxLayout(BoxLayout):
def __init__(self, **kw):
super(MyBoxLayout, self).__init__(**kw)
for i in range(3):
self.add_widget(MyLabel())
class TstApp(App):
numberprop=ConfigParserProperty(3, 'one', 'two', 'app',
val_type=int, errorvalue=41)
def build_config(self, config):
config.setdefaults('one', {'two' : '70'})
def build(self, **kw):
return MyBoxLayout()
if __name__ == '__main__':
TstApp().run()