Установить свойства виджета в PySide можно не только через соответствующие методы и конструктор класса. Можно их изменять с помощью метода setProperty по имени.
btn = QPushButton("Click Me")
btn.setProperty("flat", True)
Это аналогично вызову
btn.setFlat(True)
Если указать несуществующее свойство, то оно просто создается
btn.setProperty("btnType", "super")
Получить его значение можно методом .property(name)
btn_type = btn.property("btnType")
Когда это может быть полезно?
▫️Можно просто хранить какие то данные в виджете и потом их доставать обратно
widget = QWidget()
widget.setProperty('my_data', 123)
print(widget.property('my_data'))
▫️ Назначая эти свойства разным виджетам можно потом отличить виджеты во время итераци по ним. Например, найти все кнопки со свойством my_data="superbtn".
Но ведь вместо кастомного свойства можно использовать objectName, будет тот же результат.
Да, но y ObjectName есть ограничение - только строки.
▫️ Если нам потребуется не просто поиск а, например, сортировка по числу, то свойства позволяют нам это сделать. Поддерживается любой тип данных
widget.setProperty('my_data', {'Key': 'value'})
widget.setProperty('order', 1)
all_widgets.sort(key=w: w.property('order'))
Но ведь Python позволяет всё вышеперечисленное сделать простым созданием атрибута у объекта
widget.order = 1
widget.my_data = 123
Да, но я думаю что не надо объяснять почему не стоит так делать. К тому же, если у виджета нет свойства то метод .property(name) вернет None, а отсутствующий атрибут выбросит исключение.
▫️ Действительно полезное применение кастомным свойствам - контроль стилей. Здесь атрибутами не обойтись, нужны именно свойства.
Дело в том, что в селекторах стилей можно указывать конкретные свойства виджетов на которые следует назначать стиль.
Просто запустите этот код
from PySide2.QtWidgets import *
if __name__ == "__main__":
app = QApplication([])
widget = QWidget(minimumWidth=300)
layout = QVBoxLayout(widget)
btn1 = QPushButton("Action 1")
btn2 = QPushButton("Action 2")
btn3 = QPushButton("Action 3", flat=True)
layout.addWidget(btn1)
layout.addWidget(btn2)
layout.addWidget(btn3)
# добавим кастомное свойство одной кнопке
btn1.setProperty("btnType", "super")
# добавляем стили
widget.setStyleSheet(
"""
QPushButton[btnType="super"] {
background-color: yellow;
color: red;
}
QPushButton[flat="true"] {
color: yellow;
}
"""
)
widget.show()
app.exec_()
С помощью селектора мы избирательно назначили стили на конкретные кнопки.
Как получить список всех кастомный свойств?
Функция получения списка кастомных свойств отличается от получения дефолтных.
def print_widget_dyn_properties(widget):
for prop_name in widget.dynamicPropertyNames():
property_name = prop_name.data().decode()
property_value = widget.property(property_name)
print(f"{property_name}: {property_value}")
#tricks#qt
Morphe
https://morphe.software
https://github.com/MorpheApp
Morphe is an Android app modification tool.
It allows you to change how apps work, look, and behave beyond their original design.
Build new functionality, remove limitations, and tailor apps to your needs.
For now it supports these censored apps: YouTube, YouTube Music or Reddit.
You should boycott them, but if you are used by those propaganda apps, at least you could remove the unwanted ads
Morphe is an independent project based on prior work from ReVanced.
#yt
⚡️You-Get: Download video, audio, images from the web easily!
Ever wanted to pull a bunch of content down so you can watch later?
You-Get is a CLI (command line interface) utility that makes it easy to download videos, audio, and images from the web.
https://you-get.org
you-get 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
You Get supports an impressive array of sites: Youtube, Twitter, VK, Tumblr, Soundcloud, Instagram, Facebook, and countless others!
It supports downloading YouTube playlists as well, it'll go through each video in the playlist.
Downloads can be very slow though, I recommend you use the —info flag before downloading to see what formats are available. Then you can run the command again with the —i-tag flag at whichever quality level is right for you.
You can download videos off of big tech platforms / paywalls by using the '—cookies' flag and pointing to a Firefox cookies database (cookies.sqlite).
Alternative: https://ytdl-org.github.io/youtube-dl/
🫶@takebackourtech
#yt
#NewPipe on #Linux, Using Android_translation_layer
https://flathub.org/apps/net.newpipe.NewPipe
Comments
https://news.ycombinator.com/item?id=41963932
#yt
yt-fts - YouTube Full Text Search
https://github.com/NotJoeMartinez/yt-fts
yt-fts is a command line program that uses yt-dlp to scrape all of a #YouTube channels #subtitles and load them into a sqlite database that is searchable from the command line. It allows you to query a channel for specific key word or phrase and will generate time stamped YouTube urls to the video containing the keyword.
It also supports semantic search via the OpenAI embeddings API, Gemini embedding API and using chromadb.
Blog Post
LLM/RAG Chat Bot
Video Summaries
Semantic Search
CHANGELOG
Installation:
pip install yt-fts
#yt
SmartTube
Advanced player for set-top boxes and tvs running Android OS
Features
No Ads
Designed for TV screens
Up to 8K video resolution
Login into your account
Cast from the phone
Support tv box remote controller
Support external software keyboard
Support devices without Google Services
Open source
https://smarttubeapp.github.io
https://github.com/yuliskov/SmartTube
https://github.com/yuliskov/SmartTube/releases
WARNING NOT FULLY OPEN SOURCE
There are at least 5 proprietary libraries in the app.
https://github.com/yuliskov/SmartTube/issues/471
* Crashlytics (/com/crashlytics): Tracking
* Firebase Data Transport (/com/google/android/datatransport): NonFreeNet
* Google Mobile Services (/com/google/android/gms): NonFreeDep
* Firebase (/com/google/firebase): NonFreeNet,NonFreeDep
* Firebase Analytics (/com/google/firebase/analytics): Tracking
IzzySoft:
The 5 offenders are not permitted at F-Droid (and before you ask: I wouldn't take it into my repo either unless at least Crashlytics and Firebase Analytics are removed; 5 non-free libraries is a bit much for free/libre software).
#video#yt#androidtv
Latest release Freetube - An electron Youtube client that blocks ads (but can't avoid Google's YouTube censorship) now comes with support for sponsorblock
https://github.com/FreeTubeApp/FreeTube/releases/tag/v0.13.0-beta
#freetube#yt#YouTube