#user-interfaces
1 messages · Page 42 of 1
It's because the column is resized to fit the wide elements you have
ah that makes sense
any way around this?
Yes, but I don't know it by heart. I haven't used tkinter in almost three years.
I think you should be able to make the large widgets span multiple columns
That means you have multiple subdivisions within the width of the large ones
Ah, nice
I'm using the Tkinter module. How do you survive this design?
Can anyone help me with this problem using pyqt5, this is checkbox action to add a shortcut of an exe file to startup folder for windows. When I check the box shortcut is created and it works fine then when I uncheck then the shortcut is removed. the issue is if I check the box and restart the gui and uncheck the checkbox the program crashes. I want to know how to view the error and what cause this crash. this is the code for the function ``` def startup_action(self):
startup_path = winshell.startup()
tmp_path = r'C:\Users{}\AppData\Local\Programs\FilesOrganizer\FilesOrganizer.exe'
programs_path = tmp_path.format(getpass.getuser())
global startup_shortcut_path
if self.checkbox_startup.isChecked():
# pythoncom.CoInitialize() # remove the '#' if running in a thread.
startup_shortcut_path = os.path.join(startup_path, 'FilesOrganizer.lnk')
target = programs_path
icon = str(icon_window_icon)
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(startup_shortcut_path)
shortcut.Targetpath = target
shortcut.IconLocation = icon
shortcut.WindowStyle = 1 # 7 - Minimized, 3 - Maximized, 1 - Normal
shortcut.save()
print("Startup is triggered")
print(programs_path)
print(startup_shortcut_path)
if not self.checkbox_startup.isChecked():
file_to_rem = pathlib.Path(startup_shortcut_path)
if os.path.exists(file_to_rem):
file_to_rem.unlink() ```
I tried to call a function that remove the shortcut from another module and it worked fine but why is this happening.
@worldly venture there are other, more modern, options, than tkinter, which is indeed not great from a design standpoint
I wanna build a basic app that makes use of gphoto2 liveview via a camera
I'm kinda new to using python in regards GUI interfaces.
Would either Kivy or pyQT be able to show the liveview output from gphoto2 in the user interface?
Or would a web based GUI be better on the front end?
interestingly it seems an user just started such a project with kivy, https://github.com/jtleniger/orion
Huh wow you right @alpine blaze
Thanks, I may have to hit them up
It would technically be a live video stream @sudden coral
From camera to display on the UI
I am in need of some help developing a multi touch interface.
i am trying to build a controller like interface with two joysticks. I am unable to get the multi-touch aspect working and google isnt helping much. If anyone could help, that would be awesome
what are you using? kivy is designed for these kind of things
i was looking into pyqt, but i'm looking into kivy now
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 600, 500)
self.setWindowTitle('Title')
def window():
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
window()
What exactly from the base class do I need to use at my new class __init__?
I want to know why the program doesn't work without the super()
that's getting into the internals of Qt
there's just some behind the scenes stuff it does
if you really want to know exactly what it does then you can follow the source code here (beware it's C++) https://code.woboq.org/qt5/qtbase/src/widgets/widgets/qmainwindow.cpp.html#_ZN11QMainWindowC1EP7QWidget6QFlagsIN2Qt10WindowTypeEE
Hey, another problem, how can i keep my window ratio scaled? when i open it everything is fine but when i maximize it, the sizes of the widges are changing and not looking so good
in pyqt5
And yet another one (yes ik..), how can i make a textEdit show() and disapear()?
Just remove the widget from the layout
@sudden coral I cannot seem to find a way to delete my textEdit file
I can supply you the code, but its kind of long
Are you using a layout?
Currently, yes
def remove_tab(self, index):
widget = self.widget(index)
if widget is not None:
widget.deleteLater()
self.removeTab(index)
self.window.mainLayout.removeWidget(widget.textEdit)
widget.textEdit.deleteLater()
widget.textEdit = None
widget = None
this is how i try to remove it, but
self.mainLayout.addWidget(self.textEdit)
Oh wait i know how to fix that
hold on
OK
YES!
@sudden coral thank you <3
Now, how can i show like a welcome message under my textEdit? like create a widget or use an image and .lower() it?
Put a label widget under it
@sudden coral Hey, sorry to bother you again
I have kind of a big problem now
When i open files casually, they load up correctly
But when i close all files + the main Texteditor
I cannot open new files
ui_widgets.py -> https://mystb.in/yefabuzine.py
I hope you can help me find my problem
:D
The file is being opened by
tree.py
def on_item_clicked(self, it, col):
"""
An event handler being called by QTreeWidget.itemClicked
function uses:
Toggling folder icons
Opening Files on click (From tree view)
@param it - The TreeWidgetItem that was clicked
@param col - The column of the TreeWidgetItem that was clicked
"""
if it.item_type == "file":
self.window.open_file(self.currentItem().file_path)```
into
def open_file(self, filepath=None):
print("open")
if not filepath:
filepath = utils.openFileNameDialog()
if not os.path.isfile(filepath):
return
with open(str(filepath), 'r', encoding="utf8") as f:
e = Editor()
# try:
e.setText(self.translate("MainWindow", f.read()))
# except UnicodeDecodeError:
# pass
#filepath = os.path.join(os.path.dirname(__file__), filepath)
tab = self.tabs.create_tab(e, filepath=filepath)
self.tabs.setCurrentWidget(tab)
print("End open")```
into ```py
def create_tab(self, textEdit, filepath: str, closable: bool = True):
tab = Tab(textEdit=textEdit, filepath=filepath, parent=self)
tab.setObjectName(filepath)
# tab.padding
self.addTab(tab, "")
self.setTabText(self.indexOf(tab), self.translate("MainWindow", tab.file_name))```
@sudden coral I think the problem is
that tab change event is called in the middle of the file opening
tab change
open
tab change```
End open is not printed since the traceback is interrupting it
Yes that is the problem
Do you have any idea how to fix that?
cause the only way i can think of is very ugly
The problem specifically is that your event stops early if there is no current widget set
Maybe not
I don't know
Does it show there is already a current widget?
Yes
when i close the last tab it sais i have a current widget
lets see
And when i open it, not
We are in a middle of a problem discussion
but
@sudden coral So, if the tab is called before the open_file is ended, that is causing my problem
Maybe, if theres no current widget ill try to get the first tab
lets see
So when i close the file theres no current and when i open it it does have a current widget
hmm
@sudden coral This is interesting
I changed the code to this:
def open_file(self, filepath=None):
print("open")
if not filepath:
filepath = utils.openFileNameDialog()
if not os.path.isfile(filepath):
return
with open(str(filepath), 'r', encoding="utf8") as f:
e = Editor()
# try:
e.setText(self.translate("MainWindow", f.read()))
# except UnicodeDecodeError:
# pass
#filepath = os.path.join(os.path.dirname(__file__), filepath)
tab = self.tabs.create_tab(e, filepath=filepath)
print("E: ", e.toPlainText())
self.tabs.setCurrentWidget(tab)
print("Current ", self.tabs.currentWidget().textEdit.toPlainText())
print("End")```
and this is the output
``open
E: # BUTTON_CLICK
Current
End``
Somehow its not setting e as the currentwidget
becuase if it was, the outputs were the same
I don't know, sorry
Alright thanks man, appreciate all of your help @sudden coral
Hey guys, I have an issue with QSettings , I am saving checkbox state as config.ini file at package > resources. I have a problem when converting the script to one file using pyinstaller the settings can't be saved for some reason although I have stored my icons the exact same way. what can be the issue. note that when making a build as full folder not onefile It works perfect but the size of the files are way bigger. any help?
https://hastebin.com/hayesalotu.rb this is the code I am using.
more details here , https://stackoverflow.com/questions/59725519/qsettings-doesnt-work-after-building-onefile-using-pyinstaller
onefile works by extracing its contents to a temp dir, that has its path stored in sys._MEIPASS. So you setting the values in resources.config_ini only changes the extracted file, which is removed after you close the program
qt has a bunch of paths under QtCore.QStandardPaths.writableLocation that might be where you want to store config, like QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.AppConfigLocation) which returns .../appdata/local/{org}/{app}
Thanks solved ❤️
Hey everyone! i still got that problem, i hope anybody could help me this is really important to me.
I will make my repo public and ill tell you my problem and the code that handles it
code - https://github.com/F4zii/Shwift-Text-Editor
the code that is activated in my problem is starting here - https://canary.discordapp.com/channels/267624335836053506/338993628049571840/666366099553648653
my problem happens when i close all tabs, and the main textEditor is removed / deleted from the layer
I cant figure it out, so i will really appreciate if anybody could help me in here :D
Which operating system makes more sense?
Has anyone found a good solution for TUI with checkboxes made with click that works in both Linux, Windows and macOS? Something that looks like https://cloud.githubusercontent.com/assets/1090449/3412619/6d65cc5c-fe02-11e3-850a-f68436208980.png
Kivy @spiral citrus
Is that really for building TUIs?
can anyone help out with pyqt5 qprocess ?
self.process.start("C:\\Program Files (x86)\\foobar2000.exe /stop")```
I'm trying to get this to work ...
curses/windows-curses perhaps?
what do you mean ?
@vernal estuary what happens if you try to run this command via subprocess.Popen?
Hey @proper glade 🙂 that's what I used but thought the qprocess way would be more optimal
it'd certainly save you having to reinvent certain wheels (signals etc)
i wanted to see if the command was failing to run due to a permission error or something
and subprocess does a better job of error reporting to that effect
how about passing /stop as a separate param? iirc you can do this right?
self.process.start("C:\\Program Files (x86)\\foobar2000.exe", ["/stop"])
Thank I'll check it a bit later when I get back home 🙂
aaaand it doesn't work @proper glade
p = subprocess.Popen(["powershell.exe",
"cd 'C:\\Program Files (x86)\\foobar2000'; .\\foobar2000.exe /stop"], stdout=sys.stdout)
this the other code that worked
but that one used powershell, which is not important
I tried more than 10 combinations but couldn't get it to work
including copy pasting from the parentheses
How can I convert a .ui file to .py in MacOS? pyuic5 doesn't work.
@tulip frigate @spiral citrus i can confirm that kivy is NOT for building TUIs, for that curses is certainly the most common option
Ahh TUI my bad, misread sorry, yes Curses is probably the best for what you are after Oskar
Plus I'd say Blessed which is build on curses for a bit easier interfacing
How can I convert a Qt Creator .ui file to .py in MacOS? pyuic5 doesn't work. I thought I remembered seeing it as one command for the MacOS alternative to pyuic5 -x file.ui -o file.py, but I can't recall it.
I'd like to see some working examples of Python based scripts using Electron for the GUI.
Only (outdated) open source project I could dig up is this:
https://github.com/fyears/electron-python-example/tree/6aa92abd8bafa76e878a0e7a6fb441617ea9d062
Please post some more examples, if you know any.
a bit curious of the why, as electron is basically only goin, to cater to js
Well I want to create a nice GUI for an existing .py script
Since I'm ok with html/css and surely would need help with JS, i thought this is the wtg
using images and background colours, you can make a UI in python
@steady siren Sounds not too shabby, if it supports PNG images.
What's the wtg then? tKinter?
oh
im stupid
yeah, maybe tkinter
but im not sure what they're trying to to do
*ur
hmm, lemme show u
kk
Made in Winforms - But want something like that interacting with Python script , which has its own restful API
honestly, i'm just playing it by ear since i learned python like two days ago
@quartz mural why u prefer pyqt5 ? i'm worried about all these bindings
if you're just asking about UI, then yeah i prefer pyqt5
was easier for me to work with and personally seems like it's capable of more
what are you trying to do again Bas?
Well, I got skills in WinForms.
I got a friends python script that works with its own restful API.
I want to create a nice GUI for his script.
Preferably thru Winforms / C# , since that's my game.
Altho...
Then it won't be crossplatform anymore.
So a nice looking GUI with either Tkinter, pyqt5, Eel, Pywebview, Electron.js.
if it's already natively python, you should honestly just use python
unless his script has command line arguments that can easily be handled, it's not going to play nice
personally i would use tkinter
since it can be embedded in their cod
they're completely different things...?
are you saying he runs a restful API with a python script and you want to utilize it?
i'm saying i want to make his python script more user-friendly building a GUI for it.
ok
i just stole this from my code, but something like this? msg_list = tkinter.Listbox(messages_frame, height=100, width=100, yscrollcommand=scrollbar.set)
is it a script that sends information to an API he has elsewhere, is it an API itself that is run through the script, etc.
tell him to put it on github, it's better
ironically you say no CLI but this is a CLI script...nice
i may or may not be biased
CLI arguments I meant
this way i could easily use these to make it work from my existing winforms gui.
but that's not an option.
yeah no, just port it to C or use pyqt5 etc.
pyqt5 it is i guess then
also, those are CLI arguments. it's interacting with his scripts through CLI, sending arguments passed from it
maybe i'm confused what your defintion of CLI arguments are vs. mine
okay, when you said this was an API
you made it sound like it was a hosted APi that could have requests made against it
then you said it's his python script and it's used in CLI
CLI arguments anywhere, in any language, are arguments passed from command line when executing a program
yep it's using it's own restful api
.
yes
well, do u see such for this project?
yes, they're blatantly there on the front page you linked me
?
he also has an API as an option
which you can utilize with your winforms by simply running the python script before your winform
that's why i was asking you what you were going on about
just link your winforms buttons to actions that make post requests to the local API
that's all you need
sounds so easy 😮
once you know the endpoints and whatnot it should be
i made my own winform based on a game's API before, so i can help a little.
the endpoints are decribed on his repo
yes, i know
so no problem either then
since this is no longer python related i suggest taking anything further about it to other channels
So I'm just getting started with Kivy and async(io), I guess I want to know what's the best/cleanest way of doing async http requests in Kivy? I see Kivy has UrlRequest but it uses callbacks and doesn't seem as neat as aiohttp, but if I want my app to run on say Android would that work easily? (I'm not too sure either how building an app for Android would work i.e. how the dependencies translate etc)
UrlRequest was kind of necessary before asyncio was a thing and kivy started supporting it, i would assume you don't need it now if you use aiohttp
building the app for android will involve compiling python and kivy for arm to run on android, we default to python3.7 on android, so asyncio shouldn't be a problem, but asyncio is not in the latest release yet, only in master version, so you would need to indicate that you depend on that to buildozer
@fathom crypt
thanks I'll go with aiohttp and take it step by step, I'll be back in a few days probably when I get to the build stage 😄
Hello there guys! i am creating my text editor with pyqt5, and i wanted to ask something
how can i update the treewidget whenever a file is added to the directory (or dragged into the texteditor 😳 [only if you know])
And also another one, how can i show an image per tab? if an image file is opened
Use QFileSystemWatcher
@dawn glacier can i download it? i'd like to test it
Sure
@sudden coral Thanks, ill try!
Hi, can TKinter's tk() and tkk can be used in the same program?
anyone happen to know what a more updated use of "appindicator.CATEGORY_APPLICATION_STATUS" is in gi?
@scarlet hamlet Yes they can
Does anyone here have any experience with matplotlib and PyQT5? attempting to plot a graph into my program. It appears to be working but the figure size is not adjusting.
(not full code just a segment associated with the graph)
https://paste.pythondiscord.com/yekofakoqi.py --- code for the graph function.
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
self.assetlabel = QLabel(self)
self.assetlabel.setGeometry(20, 10, 410, 30)
self.assetlabel.setText("Asset Distribution")
graphfont = QtGui.QFont()
self.set_font(graphfont, 16, True, 70, False)
self.set_formatting(self.assetlabel, graphfont, QtCore.Qt.AlignCenter, parentypeSheet)
self.asset_Figure = Figure()
self.assetCanvas = FigureCanvas(self.asset_Figure)
self.assetFrame = QFrame(self)
self.assetFrame.setGeometry(20, 50, 410, 325)
self.assetFrame.setMaximumWidth(410)
self.assetFrame.setFrameStyle(1)
self.assetLayout = QVBoxLayout(self.assetFrame)
self.assetLayout.addWidget(self.assetCanvas)
nested_asset_snapshot(self.refUserDB, self.assetCanvas)
@rustic vector: Here is what I got when I tried to run my program:
Traceback (most recent call last):
File "C:/Users/Zero/OneDrive/(0) SacState/ECSJC/ECSJC_SignIn.py", line 63, in <module>
MyGUI = ECS_Interface(tk)
File "C:/Users/Zero/OneDrive/(0) SacState/ECSJC/ECSJC_SignIn.py", line 37, in init
OrgSelect = tk.Combobox(GUI, self.OrgList)
File "C:\Python\Python37\lib\tkinter_init_.py", line 2101, in getattr
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'Combobox'
My Program is a sign-in system, with some File IO, but the IO seems to be working, it's the TKinter parts that explode because of the tk and tkk calls....
guys, trouble in creating a virtual env, somebody could help me out? i want a venv with python 3.6
i'm using 3.8
and my command line is wrong somehow
never tried to get back versions of python on venv
Do you have 3.6 installed?
Hey there!, i have a problem with pyqt5 in macOS, the menubar is not responding, also the mac icon (which souldn't be affected), the shortcuts are working, but clicking on the menubar isn't working very well
The code for my project can be found here
if you need more specific details, i can provide them too
I have a problem running kivy. Whenever I try to start an app I get the error
Traceback (most recent call last):
File "C:\Users\Daniel K\Documents\Python Projects\main.py", line 1, in <module>
from kivy.app import App
ModuleNotFoundError: No module named 'kivy'
I tried uninstalling and reinstalling it, moving the main.py file around, crating an virtual env and installing there, nothing works. Any ideas I haven't tried?
@fast magnet seems you are not running the project with the python/venv you installed kivy şor
If you are using pycharm or another ide, check in project settings
I use sublime. What I don't get why it does not work even when I install it globally. I had a problem with a flower that did not like me having a space in my user folder name - could that have something to do with it?
Ok, run pip freez and check kivy is in it
yes, 1.11.1
And if you run python -v then import kivy in it, what do you get?
it does something, hundred lines of output... if I scroll up i can see some errors. but after that, still does not work
I am beginning to suspect a fresh win install would be best. When I started coding Python a few months ago i somewhat recklessly installed python 3 and some packages without really knowing what I am doing. Maybe I messed something up then. Also, the space in my users folder really is a pain - most programs can deal with it, but installing a modul from kivy garden would not work, so I had to make a new folder at root for an virtual env.
Can you share these undreds of lines in a pastebin?
i meant to type import kivy from inside python
oh XD sry wait i'll try it
started Anaconda prompt, python -v and after that import kivy
something happens, but I am not shure what that means. but I see no error if I am not mistaken
yes, it seems to have happily imported kivy
all the text comes from the -v flag (verbose) we added, but aside that it shouldn't be any different from when you run your code.
maybe now try "from kivy.app import App" in the same python shell?
ImportError: cannot import name 'APP' from 'kivy.app' (C:\Users\Daniel K\Miniconda3\lib\site-packages\kivy\app.py) last line
oh, typo
no error
meaning I tried importing there ant it throws no error. I strongly suspect my PATH is somehow fucked up. Had problems getting sublime to work - meaning build my python code . Took me quite some time to get it running. I think clean install would be best, get a blank slate, be precise in using virtual env afterwards.
ok
I don't know, i guess it's just how you run code with sublime, yes
But you can run from cmd anyway
Also maybe try vscode instead of sublime, it's more complete
Thanks for the help anyway. Will reinstall windows when I have the time. I am confident it will work afterwards. And thanks for the tip regarding vscode, will check it out 🙂
Hello guys, how can i set a TreeWidgetItem expandable without having any children?
is that a kivy question?
if not, you might want to say what GUI framework you are using.
Pyqt5, my bad
ok, maybe someone will know, i don't 🙂 good luck
@dawn glacier try calling .setChildIndicatorPolicy on the item with QTreeWidgetItem.ShowIndicator as an argument
Thanks, i think it works
awesome
@proper glade now i get another problem
When i expand the object his childs are not shown
i have problem with pyqt5 ans pyinstaller
i cant make my script exe
with the error ImportError: unable to find Qt5Core.dll on PATH
What's your pyinstaller version?
3.5
ohh i fix it i downgrade the pyqt5 version to 5.12.2
Upgrading pyinstaller would be the better way so you have everything up to date
Not sure on the exact command now, but when you do that I believe it should show it. Or last resort is to uninstall and install
and how i can make the program start without the terminal behind?
i want to see only the ui
Pyinstaller has a bunch of command line arguments or the spec file you may want to look at make your app a bit better
i mena
Think it's --noconsole for that
when i just run the script as .py the terminal open
the .pyw file extension is usually linked to that
wait i update both of them let me check if i can exe first
The arguments/spec stands anyways if you want to keep any settings or include assets like icons
wait what do u mean?
ohh it work with update xd
thanks u the update and the no console works :0
@dawn glacier i thought you wanted the item to seem exapandable without children?
at first yes
But after it got clicked i want them to see the children
Thats the case:
-
i create a TreeItemWidget for every file and directory (not the files that in them, yet) in the chosen folder
-
for each folder i want to show the expandable sign, even tough they have no children, yet
-
when they get clicked i add their children and show them
@proper glade
The first 2 steps are working
the last one is what im struggling with
you can attach a signal to the qtreewidget's itemExpanded signal which will pass along the expanded item
Thats already done
then inside the slot you can populate the item in a thread
def on_item_expanded(self, it):
if it.item_type == "dir":
print("Here")
if not it.was_expanded:
load_filesystem_view(it.file_path, it)
it.was_expanded = True
self.toggle_folder_icon(it)```
And its connected to the signal
ignore the prints
you can use various modules like pathlib or os.walk to get the files/folders inside the path pointed to by the item
then add new children to the item based on these
I did it in the past
But its very slow for large folders
So i only load children when item is expanded (only once)
you can do the work in another thread
then send back info using a signal to add individual items
Ow
when the item is expanded, start the thread
when it's closed, stop the thread
etc
it won't freeze the ui thread at least
class PathWalkThread(qt.QThread):
new_item = qt.pyqtSignal(str)
def __init__(self, base_path):
self.base_path = base_path
def run(self):
for path in pathlib.Path(self.base_path).iterdir():
self.new_item.emit(str(path))
# then later on in your code:
walk_thread = PathWalkThread(r'C:\Users\admin\Documents')
walk_thread.new_item.connect(lambda path: add new child here)
walk_thread.start()
something long those lines
and maybe a delay every x items to give some room to breathe
btw, there's a QFileSystemModel you can check out
you can set a QTreeView's model to a QFileSystemModel and it'll automatically take care of all this stuff for viewing a file tree
Is this including all files in subdirectories?
no, iterdir only goes one level deep iirc
I tried QFileSystemModel, but its kinda ugly
ah alright
yes i think so
if you can make your own subclass of QFileSystemModel that overrides its data method then you should be able to provide your own icon provider
ill take a look, thanks
Well, im kind of struggeling with this method
Can you tell me whats the best way to complete my current methods with threads?
@proper glade
The thread you sent, is returning all of the files in a certain dir ?
Ok i tested it now
Does the thread runs until complete?
one way to go about it could be when an item is expanded, set up a new thread object and make sure it's stored somewhere. for example have a custom QTreeWidget class with a variable specifically for the thread object. then start this thread.
yes, iterdir returns files/folders in a certain directory
I already have lots of custom classes
then these are passed along to the signal
So shouldn't be a problem
Oh so connect this signal to a function that adds items to tree?
But when will i know if the current emitted file is in a subdirectory or main one
also yes the thread will run til complete.
great
But when will i know if the current emitted file is in a subdirectory or main one
not sure what you mean by this. you can set up the thread signal in such a way that that the callback knows which item to add new children to
e.g. walk_thread.new_item.connect(lambda path: parent_item.addChild(create new item based on path))
Maybe ill just build a treewidget item and send it?
or you can pass in the parent item using the thread's constructor
but that coupling is probably not a great idea with regards to garbage collection
im not sure about sending treewidgetitems across threads
there might be some hidden weirdness there
but maybe worth a try
Wait how can i connect a signal from one file to another
just import the thread and get his field?
Yep
Got it
from threads import PathWalkThread
class TreeFileWidget(QTreeWidget):
self.path_walk_thread = PathWalkThread(dirname='.')
self._update_signal = self.path_walk_thread.tree_view_modified```
Like so?
that looks about right
just keep in mind that if you want to replace the path_walk_thread to replace_update_signal too
and of course that needs to happen inside __init__ if you want to use self
Yep
its in there
just wanted to paste relevant code
Wait
You are right
if i want to change the thread, which i want
every time i open a folder
How can i make this better? so i won't need to change both at the same time
def change_thread_dir(self, path: str):
self.path_walk_thread = PathWalkThread(path)
self._update_signal = self.path_walk_thread.new_item```
maybe a util like this?
you could remove _update_signal altogether, just use path_walk_thread.new_item when required
what youre showing there is the exact same
youll still need to modify both
i think there's been a misunderstanding here about how singals/slots work
setting one object's variable to another's signal doesn't connect them in any way
it's just another reference to the same signal
you have to use the signal's connect method to perform the connection
yep
it works
It is not recommented to send items / trees via signals? @proper glade
It will make my life way easier
ive never tried it. not sure if it'll work as expected
Aight i will try
you might need to call the items' moveToThread method one theyre received in the main thread
with QApplication.instance().thread() as argument, to get a reference to the main thread
https://doc.qt.io/qt-5/qobject.html#moveToThread
Warning: This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread. There is one exception to this rule however: objects with no thread affinity can be "pulled" to the current thread.
so it might work, it might not
class PathWalkThread(QThread):
new_item = pyqtSignal(str)
tree = QTreeWidget()
def __init__(self, base_path = QDir.currentPath()):
super().__init__()
self.base_path = base_path
def run(self):
self.load_filesystem_view()
self.new_item.emit(tree)
def load_filesystem_view():
"""
Load Project structure tree
@param startpath
@param tree
@return
"""
if not startpath:
return
if isinstance(tree, QTreeWidget):
tree.clear()
for element in pathlib.Path(self.base_path).iterdir():
path_info = startpath + "/" + element
parent_itm = QTreeWidgetItem(tree, [os.path.basename(element)])
parent_itm.file_path = path_info
if os.path.isdir(path_info):
parent_itm.setIcon(0, QIcon(DIR_CLOSED_ICON_PATH))
parent_itm.item_type = "dir"
parent_itm.was_expanded = False
parent_itm.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
else:
parent_itm.setIcon(0, QIcon(get_icon_for_extention(element.split(".")[-1])))
parent_itm.item_type = "file"
I will try this one
load filesystem is working, so i just want to look if the other code it correct
i dont think this is a good idea
i thought when you said you wanted to send a tree over the thread you mean like, tree in the abstract sense, as in a tree of paths/items
not an actual QTreeWidget
probably not, and youll likely need to make sure to call moveToThread on the items once received
but give it a try, might be fine
btw, the new_item = pyqtSignal(str) line means that this signal sends out a str as its argument
youll have to change str to the type of whatever it is you want to send
ye i should change that
@proper glade ok
now ive emitted the tree
Sorry the treeItem
Ohh so now whenever a folder is expanded i call the thread?
start the thread, yep
And then i replace the given item with the current
def on_item_expanded(self, it):
if it.item_type == "dir":
print("Here")
if not it.was_expanded:
self.path_walk_thread.start()
it.was_expanded = True
self.toggle_folder_icon(it)```
But then when can i assign the item into the tree?
im not sure you can do that. the method i had in mind was to populate the current item with new items, not replace it
you could probably get the index of the item using a method then replace it using that
as for when, you do it when the signal is emitted
by connecting a callback to it
the current widget of what?
current item sorry
oh right, yeah, but that wouldnt be too reliable. the current item could change between the start of thread and the emission
Yep thats why its dangerous
mmm
:(
ill try emitting a tree like a gangsta
And see if it works
@proper glade It is workin, but thres an error
(Make sure 'QVector<int>' is registered using qRegisterMetaType().)
QObject::connect: Cannot queue arguments of type 'QVector<int>'
(Make sure 'QVector<int>' is registered using qRegisterMetaType().)
QBasicTimer::start: Timers cannot be started from another thread
QBasicTimer::start: Timers cannot be started from another thread```
Not so sure what it means
no traceback
no so sure also
@proper glade You got any idea? checked for connection or emits and found no one that is in no use
should i use moveToThread?
Where exactly? im not quite familiar with this
inside the callback
e.g.
def item_received(item: QTreeWidgetItem):
item.moveToThread(QApplication.instance().thread())
# do other things with item
walk_thread.new_item.connect(item_received)
I removed the connections
Im just changing the tree by his instance
Not instance
sorry
Itself
you can't do that across threads
signals/slots are necessary for cross thread communication in qt
yes, you can use moveToThread
Lets start all over (if you can still help me after all my bullshiit lmao)
So
I have a thread
That gets a tree
And changes it
I need to use moveToThread to be able to write/read into it?
class PathWalkThread(QThread):
def __init__(self, tree: QTreeWidget):
super().__init__()
tree.moveToThread(QApplication.instance().thread())
self.tree = tree
self.tree.clear()
self.base_path = self.tree.dirname```
no. that'll mess all kinds of things up
mmm
rather than replacing the tree, or trying to move it into the thread, you can use the thread to generate new paths/items
then send these over to the main thread using a signal
and then connect a callback to this signal to create/add new items
But the problem is how can i know where to insert the sent items
you set up the callback in such a way that keeps track of that
in the signal for onItemExpanded you are given a reference to the item
you can use this reference in the callback
this is quite weird and hard to achieve
for me
Ill try to load the children everytime the folder was clicked
thanks for the help anyways!
If you could help me some more it'll be great, but you can go if you need :D
@proper glade Are you sure i cannot create an empty item which is expandable? (just shows nothing cause it has no children)
if you all the item's .setChildIndicatorPolicy with ShowIndicator as argument then that's essentially what the item becomes
@dawn glacier
Did it
but still
Wait
Wth
Why not it works
hold up
Oh well
thats bad
RecursionError: maximum recursion depth exceeded while calling a Python object
def on_item_expanded(self, it):
print("here")
if it.item_type == "dir":
load_filesystem_view(it.file_path, it)
self.toggle_folder_icon(it)```
With those funcs
def load_filesystem_view(startpath, tree):
"""
Load Project structure tree
@param startpath
@param tree
@return
"""
if not startpath:
return
if isinstance(tree, QTreeWidget):
tree.clear()
for element in os.listdir(startpath):
path_info = startpath + "/" + element
parent_itm = QTreeWidgetItem(tree, [os.path.basename(element)])
parent_itm.file_path = path_info
if os.path.isdir(path_info):
parent_itm.setIcon(0, QIcon(DIR_CLOSED_ICON_PATH))
parent_itm.item_type = "dir"
parent_itm.was_expanded = False
parent_itm.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
else:
parent_itm.setIcon(0, QIcon(get_icon_for_extention(element.split(".")[-1])))
parent_itm.item_type = "file"
what happens in toggle_folder_icon?
def toggle_folder_icon(self, item):
# loop = QEventLoop()
# QTimer.singleShot(10, loop.quit)
# loop.exec_()
expanded = item.isExpanded()
if expanded:
item.setExpanded(False)
item.setIcon(0, QIcon(DIR_CLOSED_ICON_PATH))
else:
item.setExpanded(True)
item.setIcon(0, QIcon(DIR_OPENED_ICON_PATH))
Nothing serious i guess
Its in os.path.basename
as said in the traceback
File "c:\Users\iddos.DESKTOP-JTOR36M\Documents\GitHub\Shwift-Text-Editor\src\widgets\tree.py", line 65, in on_item_expanded
load_filesystem_view(it.file_path, it)
File "c:\Users\iddos.DESKTOP-JTOR36M\Documents\GitHub\Shwift-Text-Editor\src\utils.py", line 66, in load_filesystem_view
parent_itm = QTreeWidgetItem(tree, [os.path.basename(element)])
File "c:\Users\iddos.DESKTOP-JTOR36M\Documents\GitHub\Shwift-Text-Editor\venv\lib\ntpath.py", line 214, in basename
return split(p)[1]
File "c:\Users\iddos.DESKTOP-JTOR36M\Documents\GitHub\Shwift-Text-Editor\venv\lib\ntpath.py", line 184, in split
seps = _get_bothseps(p)
File "c:\Users\iddos.DESKTOP-JTOR36M\Documents\GitHub\Shwift-Text-Editor\venv\lib\ntpath.py", line 35, in _get_bothseps
if isinstance(path, bytes):
RecursionError: maximum recursion depth exceeded while calling a Python object```
looks like a stack overflow rather than an actual recursion error
don't seem to be doing any recursion from what i can tell
same here
Tried to open a folder with one item for testing, it also happens
Weird
the issue is cause due to trying to generate the entire tree at once
not due setting child indicator policy
Its not the whole tree
Its the item
for the first time its a tree
but that is not the problem
the problem is when i try to expand an item
oh item.setExpanded will trigger the expansion signal
no worries
Now it works!
great
Just one problem
Ill prbably know how to fix it
so
Omfg!!!
@proper glade ily, thanks
You served most help (tv show reference lul)
No really, you were so helpful, thank you very much
<3
no prob, glad it woked out
Are you familiar with QFileSystemWatcher?
a bit, yeah
Well im trying to listen into directory changes
So what i thought about was
Running a thread
And sending signals whenever the directory changes
and if it was changed, reload its view
Sounds ok?
dont think another thread will be necessary
Oh alright
qfilesystemwatcher will run its watching methods in another thread automatically
you just gotta connect stuff to its signals
mm alright
So how can i use it?
Just call a method under QFileSystemWatcher?
ill check it out
hold on
self.watcher = QFileSystemWatcher(['.'])
So i initiallzie it like so
And when i open a folder
I remove all the paths
and add the current folder path?
you could either create individual QFileSystemWatcher objects for each folder, the hook up the directoryChanged signal for that specific object to the update callback for that specific folder's item or
set up some way to associate paths with items, such as a dict
then have one main QFileSystemWatcher hooked up to one central update callback that updates the item associated with that given path
you could add/remove directories to the watcher when their items are expanded/collapsed
thatll avoid using resources unnecessarily for folders you dont need to be updating
but then youll have a problem if the folder changes while the item is collapsed
so maybe you could have a flag on the item thatll indicate if it's been changed since it was last expanded
then update its children is this flag is on when expanded again
i'm not sure how well QFileSystemWatcher's performance scales
Does it watch subdirectories also?
dont think so
Whats a better way to set a settings window?
Like for the user to choose a font family, size, theme, etc
A new window, or a widget?
that's really a matter of preference i suppose
Do you guys have any idea why my pyqt5 Gui runs so slow on MacOs but on windows its very fast?
And also
# ['Breeze', 'Oxygen', 'QtCurve', 'Windows', 'Fusion']
app.setStyle('Fusion')```
Only Fusion works with my mac
The other styles make the tabs look messy and create them in the other side of the tab bar
And also 'windows'
I made an html that display a table from mysql, can i make some sort of ui that changes data to the db, like an edit button or add column button, I’m not familiar with ui is this even possible?
I have absolutely no idea what channel this should go in, but I'm trying to develop a user interface so here goes: Does anyone know of a python module to interface with MPRIS? I've found a few, but the more recently updated one hasn't seen a commit since 2016, and I don't feel like basing a project on that.
Are there other Ways to create an Interface without tkinter?
Question in PyQt5: How can i connect Keyboard and a button ,so when i press a button(Keyboard) a button in program is pressed?
Well, you need to handle the keyPressEvent and press the button yourself
def keyPressEvent(self, event):
print(event.text())
i did that then it said that event is undefiend
You probably want a if not event.isAutoRepeat(): in there as well so that holding down the key doesn't trigger it multiple times
That function should be part of a QWidget, I think
yes
let me see again wait
ok it gone but now it says : 'Ui_Sensor' object has no attribute 'text'
Sounds like you're doing something other than event.text()
def keyPressEvent(self, event):
print(event.text())
theres just event.text method
i guess its somehow not implemented or something
im not understanding im like noob in python
Well, if your event is a Ui_Sensor object then that isn't what you want, you want a QKeyEvent object
yes
so that's what isinstance() does, it checks whether an object is of a specified type
tell me where to fit it
you'll have to import QKeyEvent, of course, from wherever it comes from
Have you covered conditionals yet?
so import QKeyEvent ?
I have no idea what module it's actually in
I suppose it's probably within PyQt5.QtGui
so from PyQt5.QtGui import QKeyEvent
(that's at the top of your file)
and of course that conditional needs to be added to your function
if isinstance(event, QKeyEvent):
print(event)
I suggest just printing the event object
you'll probably get more useful information from that
yes i had that but it sayy event not defined
Give me the full traceback
Well then you've placed it outside of your keyPressEvent function
ah ok 😄
ok now it runs program no error so when ipress space one button is activsating
oh, are you trying to catch the space keypress? you probably can't just do that
space usually presses the currently selected button
Okay
Well this is about as far as my familiarity with Qt goes, but I suppose you'll have to check what the key being pressed is and decide what to do based on that
you'll need to be able to actually get at your button within your code in order to press it, of course
yes i checked on web
but where am i supposed to fill that info(key)
now its like that
def keyPressEvent(self, event):
if isinstance(event, QKeyEvent):
print(event.text()
You're missing a closing bracket on that last line
miss copy
You'll probably need to look at the docs for QKeyEvent to see what APIs it exposes
hold on
so, it looks like there are constants defined
for example, Qt.Key_W
This is an example of someone doing that
so you'd be doing something like
if event.key() == Qt.Key_W:
my_button.press()
Huh? can you rephrase that question?
how can i post you the full script for better look?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ok let me explain my idea
Any changes you make to this file will be lost if you change the UI file and regenerate the class with the UIC tool
yes, that's what I'm saying
do that again and you will lose your changes
this is not the intended way to make use of these classes
I mean, yeah, it will be a problem, if you edit the UI in the designer again
yes but i wont 😄
Like streamers when they have a windows with w,a,s,d and u can see what their pressing in the moment
I think you're going to run into issues with that, aside from what we've discussed already
I don't think you can just set up a global hotkey that's a single letter in Qt
so i cant relate the w button to the w button in progam?
Not unless the program is in focus
There are ways around this, I just don't think Qt provides one
but it hasnt to be Qt .I could use any module to that program.Do you know a method?
I actually don't know any off the top of my head
By the way, though
Have you used any specific Python learning materials?
i just learned from Videos like Playlist so just basics
Corey Schafer?
nope german like Morphus
Ah okay, I wouldn't know
I will say that GUI work can be a fairly advanced topic, especially when it comes to a complicated framework like Qt
If you want something a bit easier, there's always Kivy, tkinter, PySimpleGUI
On the other hand
I don't think wiring up buttons in this case is actually what you want
Why not just have a label or a set of labels that shows all of the keys being held?
I mean, I wouldn't say it's much easier, but it makes more sense than trying to create a button for every single key you want to show
no the buttons are already created i just want to activate them when pressing key
Alright
Well, personally, I'm at about the limit of my knowledge
It's 1AM (or later) here in Europe so it's going to be quiet for a while
i think im not good at explaining
can u give me some advice what is easy to learn for beginners and is very usefull?
Honestly, the best advice I can give to someone at your level of experience is to hit the books
You can keep hammering away at your problem and eventually you'll get there, I'm sure
But all the resources I know are in English
They both work
but if you're going with videos, you want to make sure you have a good series
okay but thanks for your help !
If you do end up needing more resources though, https://pythondiscord.com/pages/resources/
ok
please someone help me 🙂 in Help 5
Been trying to figure out a method of essentially "refreshing" or redrawing a matplotlib graph that I have placed into a PyQt5 Qvboxlayout. I have tried a variety of clear(), clf(), destory(), removewidget(), removeitem() to no avail. I can't seem to refresh this image. Any thoughts?
Code wise - this how i build the item for display
self.assetlabel = QLabel(self)
self.assetlabel.setGeometry(20, 10, 410, 30)
self.assetlabel.setText("Asset Distribution")
graphfont = QtGui.QFont()
self.set_font(graphfont, 16, True, 70, False)
self.set_formatting(self.assetlabel, graphfont, QtCore.Qt.AlignCenter, parentypeSheet)
self.asset_Figure = Figure(dpi=200, facecolor="#f5fbef")
nested_snapshot(self.refUserDB, "Asset", self.asset_Figure)
self.assetCanvas = FigureCanvas(self.asset_Figure)
self.assetFrame = QFrame(self)
self.assetFrame.setGeometry(20, 50, 410, 325)
self.assetFrame.setMaximumWidth(410)
self.assetFrame.setFrameStyle(1)
self.assetLayout = QVBoxLayout(self.assetFrame)
self.assetLayout.addWidget(self.assetCanvas)
As for building the graph this link will lead the the expanded function - https://paste.pythondiscord.com/eqayoruhor.py
Any ideas or things to try would be useful. I want the graph to update with new user inputs. thanks
i need help in tkinter....any body here tkinter and opencv expert?
i need help with pyqt5
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.ButtonSent.setText(_translate("MainWindow", "Sent"))
self.label.setText(_translate("MainWindow", "Mail"))
self.label_2.setText(_translate("MainWindow", "Password"))
testvar = "Testing var"
self.ButtonSent.clicked.connect(self.testing(testvar))
def testing(self,test):
print(test)
why this is not working?
Traceback (most recent call last):
File "C:\Users\dprevazi\Desktop\DEVELOPER\GUI\test.py", line 74, in <module>
ui.setupUi(MainWindow)
File "C:\Users\dprevazi\Desktop\DEVELOPER\GUI\test.py", line 50, in setupUi
self.retranslateUi(MainWindow)
File "C:\Users\dprevazi\Desktop\DEVELOPER\GUI\test.py", line 63, in retranslateUi
self.ButtonSent.clicked.connect(self.testing(testvar))
TypeError: argument 1 has unexpected type 'NoneType'
this is the error
(im nub i just started learning about ui)
you have to connect to a callable, so a function or a method and then qt does the calling itself
Now you're passing it the return of testing (which is None)
ohh
and then how i can make when i press the button it prints my var
it will be a value on textedit but for now is var
you can use a lambda (anonymous function) or functools.partial
so lambda: self.testing(testvar) passed to the connect
how does it look with the syntax error?
it's lambda [args]: <code>
in your case you're wrapping your method call in an another function. functools.partial has more utility (and sometimes readability) if you need it in the future
testedit is a widget?
it should have a method for getting it out of it
yes is a widget
testvar = self.InMail.toPlainText()
this is k?
AttributeError: 'QLineEdit' object has no attribute 'toPlainText'
ah a QLineEdit, it's just text there
yes
you can look through the docs at https://doc.qt.io/qt-5/reference-overview.html (c++ but a bit more complete in some ways) or https://doc.qt.io/qtforpython/api.html which are quire good and will have the methods of the widgets with explanations on what they do
:/
ohh i did it
self.(name).text()
it was so ez xd
i hate object programing :/
anyway thank you ❤️

I need help with Tkinter ! 😮
Please help 😦
from tkinter import *
with open("status.txt", "r") as file:
lijst = file.readlines()```
def get_text(root,val,name):
# try to open the file and set the value of val to its contents
try:
with open("status.txt", "r") as f:
val.set(f.read())
except IOError as e:
print(e)
else:
# schedule the function to be run again after 1000 milliseconds
root.after(1000,lambda:get_text(root,val,name), lijst())```
root = Tk()
root.minsize(600,200)
eins = StringVar()
data1 = Label(root, textvariable=eins)
data1.config(font=('Helvetica', 16, 'bold italic'), foreground='#2E2E2E',background='#ffff33')
data1.pack()
get_text(root,eins,"test.txt")
root.mainloop()```
This is my full code
Which works, but i want per line of the file that the font is different
So what i tried is implementing this
for l in lijst :
text1 = lijst[-1]
text2 = lijst[-2]
text3 = lijst[-3]
text4 = lijst[-4]
text5 = lijst[-5]
text6 = lijst[-6]
text7 = lijst[-7]
text8 = lijst[-8]
if text1 != lijst[-1]:
text1 = text2```
```Python
label7 = Label(master=root,text='Most Recent: '+text1 ,height=3, font=('Helvetica', 24, 'bold italic'), foreground=blue,background='#ffff33')
label7.pack()
label6 = Label(master=root,text=text2 ,height=2, font=('Helvetica', 21, 'bold italic'), foreground=darkishBlue,background='#ffff33')
label6.pack()
label5 = Label(master=root,text=text3 ,height=2, font=('Helvetica', 18, 'bold italic'), foreground=darkBlue,background='#ffff33')
label5.pack()
label4 = Label(master=root,text=text4 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkGray,background='#ffff33')
label4.pack()
label3 = Label(master=root,text=text5 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkGray,background='#ffff33')
label3.pack()
label2 = Label(master=root,text=text6 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkGray,background='#ffff33')
label2.pack()
label1 = Label(master=root,text=text7 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkishGray,background='#ffff33')
label1.pack()
label = Label(master=root,text=text8 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=gray,background='#ffff33')
label.pack()```
But now it shows 2 lists
root = Tk()
root.minsize(600,200)
eins = StringVar()
data1 = Label(root, textvariable=eins)
data1.config(font=('Helvetica', 16, 'bold italic'), foreground='#2E2E2E',background='#ffff33')
label7 = Label(master=root,text='Most Recent: '+text1 ,height=3, font=('Helvetica', 24, 'bold italic'), foreground=blue,background='#ffff33')
label7.pack()
label6 = Label(master=root,text=text2 ,height=2, font=('Helvetica', 21, 'bold italic'), foreground=darkishBlue,background='#ffff33')
label6.pack()
label5 = Label(master=root,text=text3 ,height=2, font=('Helvetica', 18, 'bold italic'), foreground=darkBlue,background='#ffff33')
label5.pack()
label4 = Label(master=root,text=text4 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkGray,background='#ffff33')
label4.pack()
label3 = Label(master=root,text=text5 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkGray,background='#ffff33')
label3.pack()
label2 = Label(master=root,text=text6 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkGray,background='#ffff33')
label2.pack()
label1 = Label(master=root,text=text7 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=darkishGray,background='#ffff33')
label1.pack()
label = Label(master=root,text=text8 ,height=2, font=('Helvetica', 16, 'bold italic'), foreground=gray,background='#ffff33')
label.pack()
data1.pack()
get_text(root,eins,"test.txt")
root.mainloop()```
And list 1 doesnt update ofc
This may be a very basic question, but how would one e.g. call an async function on button press in Kivy? I've tried googling and can't find a straight answer.
this may help https://github.com/kivy/kivy/pull/6368 but not that familiar with async
Hmm yeah saw that but from a brief scan I couldn't find anything useful
Or maybe I don't understand it well 😄 I thought you could just throw an await in the .kv file lol
(PyQt5) My textEdit derives from QPlainTextEdit, and when i scroll down it get stuck and not scrolls until EOF (end of the buffer/file)
hmm that is weird AttributeError: 'Editor' object has no attribute 'setText' class Editor(QPlainTextEdit):
@fathom crypt if you are using kivy master, that might work, but same, no xp with async yet
So... this is (probably?) a massive hack but if I do :set loop asyncio.get_event_loop() at the top and then on_release: asyncio.run_coroutine_threadsafe(app.authenticate(), loop) it works. Anyone see any major problems with this?
are you running an async app?
Yeah I have a loop.run_until_complete(SMSApp().async_run())
Turns out I can just use create_task(). Shows how deficient my async knowledge is 🙃
class Editor(QPlainTextEdit):
def __init__(self, centralwidget):
super(QPlainTextEdit, self).__init__(centralwidget)
self.setGeometry(QRect(180, 40, 1650, 850))
self.textEdit = Editor(self.centralwidget)
self._window.textEdit.setText(curr_tab.text)
AttributeError: 'Editor' object has no attribute 'setText'
Im using pyqt5, anybody got an idea what might be the problem here?
QPlaintTextEdit doesn't have the setText slot
last time you asked in a help channel and probably missed it, but think it was something like setPlainText; the docs will have them all listed nicely when you don't know the right one
!d g PySide2.QtWidgets.QPlainTextEdit
class QPlainTextEdit([parent=None])```
>
> > QPlainTextEdit(text[, parent=None])
> >
> > param parent [`QWidget`](QWidget.html#PySide2.QtWidgets.QWidget "PySide2.QtWidgets.QWidget")
>
> param text unicode
>
> Constructs an empty [`QPlainTextEdit`](#PySide2.QtWidgets.QPlainTextEdit "PySide2.QtWidgets.QPlainTextEdit") with parent `parent` .
@rocky dragon Oh alright!! thank you very much, i think i missed it, sorry for the repost
Do you guys know how to color each word in a different color in pyqt5? ive seen QPlainTextEdit.setExtraSelections(selections)
But im not sure that is what i need
Hello guys, i added a QSplitter - https://gyazo.com/c117ac701f51e6ef6195f01a616f4622
https://gyazo.com/882ce01d6cc1a1ec131ab699d5c3ed94
I would love to drag the size of the textEdit and the Tree view
i tried adding a QSplitter including both of them but then this happened https://canary.discordapp.com/channels/267624335836053506/303906556754395136/672471062700621824
is there a way to insert a child into a specific index in TreeViewWidget (PyQt5) and push all the next items forward?
which one? TreeView or TreeWidget?
not sure about TreeView but according to docs TreeWidget takes an index in its insertTopLevelItem method
https://doc.qt.io/qt-5/qtreewidget.html#insertTopLevelItem
additionally QTreeWidgetItem has an addChild method that also takes an index
https://doc.qt.io/qt-5/qtreewidgetitem.html#insertChild
regarding qsplitter, iirc there's a orientation setting you need to configure first
to make it vertical
@dawn glacier
Again very helpful, thank you @proper glade
oh huh
By default, the orientation is horizontal (i.e., the widgets are laid out side by side)
so i guess it should be working correctly by default
hmm
would you mind posting the code for the ui setup?
in particular, make sure that youre adding the splitter object to the layout after adding the widgets to it, not the individual widgets themselves.
Would anyone know how to get syntax highlighting in a Text widget in Tkinter?
what are some good tutorials to learn pyside2?
Hi. Is anyone here familiar with PyQt5?
Guys, is it viable to use Python, Flask, React and MongoDB for a full stack? 🙂
Rather, how viable is it compared to other options? 🙂 (editted the "." to "?")
i'm not a fan of mongodb, some like it but just make sure you understand the consequences of that choice
@digital rose Hover event and grid layout are easy to do with Tkinter.
<Enter> event and the grid layout manager
ight i will check that out
I don't entirely understand your 2nd message. Sounds like you want to recreate snipping tool?
well imagine a window with a grid, in each cell there's text or image. upon clicking the image/text you copy it and insert it to the previously focused window
kinda like the keybind windows+ .(period) on windows 10
but more functionality
Ahh
Hmm, that will be more difficult. Not sure if you want to use Tkinter for that then since idk if Tkinter can handle events outside of the Tkinter window. Such as detecting a keypress.
You might have to use multiple libs for that if you go ahead with Tkinter
I would have done it with c#, but c# makes the background of images grey
i had to resort to python instead of figuring out another way, because of how the internals of the .net framework are made
I'd look into the "keyboard" library and potentially Tkinter. Keyboard looks like it'll handle hotkeys outside of the Python shell and Tkinter can be used for the GUI.
I would have done it with c#, but c# makes the background of images grey
You sure there isn't a workaround for that?
Doesn't support transparency?
well, I tried finding one, I only noticed it after the whole program was finished which kinda sux
What lib were you using for it?
the Windows.Forms.Clipboard just doesn't somehow
Hmm
[ #python #tkinter #titlebar ]
Hi Everyone! I have a small problem with Tkinter, does anyone know how to remove title bars from windows, I have tried with "example.overrideredirect(1)" and "example.overrideredirect(True)" but with this command the window does not appear. Some idea? 🧐🤓
This works fine for me, 1 or True are the same in this sense
import tkinter as tk
root = to.Tk()
root.overrideredirect(True)
root.geometry("+400+100") # just move the window
root.mainloop()
Thanks, i try
What would be the "best" gui to use alongside sockets? Right now Im using tkinter with threading and it gets kind of messy
Pyqt/Pyside2 is probably well equiped for that, kivy works too, though not much specific to handle that, but managing the network stuff in a thread (or using asyncio) should not cause any issue.
I would like to know if anyone has experience creating custom buttons for a Mayavi interface
I'm probably overlooking something simple but I can't seem to access the root widget from my Kivy App class. I have
class SMSWindow(TabbedPanel):
pass
class SMSApp(App):
def build(self):
return SMSWindow()
``` and in `sms.kv` ```py
<SMSWindow>:
do_default_tab: False
TabbedPanelItem:
etc...
Now if I do print(app.root.ids) within the kv file (e.g. on button release) it works, but trying self.root from the App gives me None. What am I missing?
@alpine blaze ah I tried to initialise the values of a Spinner by calling a method in App but didn't release that kv lang would initialise before the build method. Thanks, got it working now.
👍
Hey guys i have a project idea and i’m currently still learning python and i just want to share my idea with you guys and if you want to work and have fun together you can dm me! I’m building kinda an interactive learning platform for Algorithm and DS, I want to have like multiple animations for an algorithm and just explain how does this algorithm work same like DS, if anyone is interested to join the boat just tell me :), but dont expect huge from me because i’m still learning if anyone want to give any guidance i would love it so much
Hi! Is there someone that could help me with a pyqt5 project?
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
is it possible to detect click events on qlabels in pyside2?
it should have a mouse press event from QWidget
and how do I set a qlabel's size to be the largest square it can be within the viewport?
for example, if the height of the viewport is 100, and width is 200, and there are 10 qlabels, how do I make all the qlabels' widths and heights 10?
how would I do that? .setSizePolicy, right?
yeah on the labels, I usually try out things like this in the designer
should be in the root of the pyside install, just designer.exe
I'm not on windows
well should be there but not the exe then I guess 😛
you'd set them to (...Expanding, ...Expanding) depending on the axes you want to set that to
but I think they'll get preferred bydefault which would expand them in a layout to take equal space
you'd set them to (...Expanding, ...Expanding) depending on the axes you want to set that to
I'm sorry - I don't think I understand!
I want to set both the height and the width to the lesser among them
like vmin in CSS, I think
and I'm unable to get designer working
QtWidgets.QLabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
Will set it to expanding, but not sure what you want to do now with the lesser and the layout laone should solve it I believe.
here's the enum for the policies and their explanations
!d PySide2.QtWidgets.PySide2.QtWidgets.QSizePolicy.Policy
PySide2.QtWidgets.QSizePolicy.Policy```
This enum describes the various per-dimension sizing types used when constructing a [`QSizePolicy`](#PySide2.QtWidgets.QSizePolicy "PySide2.QtWidgets.QSizePolicy") .
Constant
Description
QSizePolicy.Fixed
The [`sizeHint()`](QWidget.html#PySide2.QtWidgets.PySide2.QtWidgets.QWidget.sizeHint "PySide2.QtWidgets.PySide2.QtWidgets.QWidget.sizeHint") is the only acceptable alternative, so the widget can never grow or shrink (e.g. the vertical direction of a push button).
QSizePolicy.Minimum
The sizeHint() is minimal, and sufficient. The widget can be expanded, but there is no advantage to it being larger (e.g. the horizontal direction of a push button). It cannot be smaller than the size provided by sizeHint().
QSizePolicy.Maximum
The sizeHint() is a maximum. The widget can be shrunk any amount without detriment if other widgets need the space (e.g. a separator line). It cannot be larger than the size provided by sizeHint().
QSizePolicy.Preferred... [read more](https://doc.qt.io/qtforpython/PySide2/QtWidgets/QSizePolicy.html#PySide2.QtWidgets.PySide2.QtWidgets.QSizePolicy.Policy)
anyone here worked with QT Designer?
I'm unable to get it working, @wraith belfry
oh, what's the problem?
I get this error
oh im a windows user not that good with terminal/cmd stuff :/
oh
@rocky dragon have you used QT designer?
jsuta bit
i have a question about the "Object Inspector"
yep didn't use that 😄
@rocky dragon I'm still unable to set it to expanding
awh damn 😛 hehe
QSizePolicy does not have an attribute called Expanding
@past pivot you should realy try and get QT Designer running! 1000000 much easier to design the GUI 🙂
but I'm not able to find any help related to the error I showed above
I tried looking online
i asked a friend of mine 🙂 i'll report back when he is online
thanks a lot!
he is a python/pyqt5/linux dude 🙂
accessing the size policy seems to work fine for me
In [10]: QtWidgets.QSizePolicy.Expanding
Out[10]: PySide2.QtWidgets.QSizePolicy.Policy.Expanding
Could you show how you're trying to set it?
I don't even know how to import the enum
imports in python seem to be rather confusing!
from _ import _ seems to work differently from import _._
just import qtwidgets with a from import and then access it through that
from PySide2.QtWidgets.QSizePolicy import Policy does not work
from PySide2.QtWidgets import QSizePolicy and then QSizePolicy.Policy also does not work
yeah pyside has the packages in some other way
I think you have to do a from import or go some other way around it
from PySide2 import QtWidgets
actually
from PySide2.QtWidgets import QSizePolicy and then QSizePolicy.Policy also does not work
Policy exists this way
but I get this
@past pivot got an answer from my friend
I'm guessing there's a Python part (installed with pip or something) and a backing library part that is either installed with yum/apt-get/whatever or has to be compiled locally to supply the libraries.
ah alright you have to do the from import or like this; but really just import the 3 bases and then access through that or it'll become a mess imo
you need to provide the both policies, or create one that has them both in itself
so policy for x and y in the signature or create a policy and set the x y policies on it and then send that to the widget
ooh, it works!
both with from Pyside2 import QtWidgets and with from PySide2.QtWidgets import QSizePolicy
thanks a lot!
@rocky dragon actually it doesn't do what I wanted it to do
you'll have to do it with layouts, size policies and spacers if you don't want to set them manually afaik
so play with it I guess
@wraith belfry which of these is the designer you were talking about?
the first one, qt quick designer is for qt quick which comes from qml
I just installed it from pacman separately
that's it 🙂
yay!
not familiar with it but think you can put your own graphics there. I just used a QLabel for displaying images
ah then i'll use that 🙂
@past pivot @rocky dragon this was Ver. 1.0
This is the new version im working on now (^^,) looks sweet!
nice!
it's a gui to controll my 7 LED installations i have 🙂
Looks cool, is that the default theme?
alright, just got confused because it looks a bit like it but don't think it works with your own colors 😄
are those color rectangles sizes offset intentionally? Just one thing that's kinda bugging me off
hehe 😛 im a OCD person and i like dark colors 🙂 when i open a BRIGHT program in my basement livingroom it "destroys" the atmosphere of my LED installations 😛
yea they are 🙂 to fit the "design" :p
i felt the slider got way to wide so i just shrunk the 2 middle color buttons 😛
@rocky dragon have you used Tab Widget?
I'm finding it very hard to figure out how to design what I want with qtdesigner. Do you guys know of any good tutorials?
Hey guys so umm Im using Qt Designer and im trying to have a small widget that can scroll through text IN my main window, any ideas?
I believe QTextEdit supports scrolling.
@digital rose
However, I've not used it personally.
Yup I tried, i got it working, although I have another problem
I want to make a small box, where inside it will show information like a list, but with colums, such as :
Username | AFK | Rank | *other stuff*
Kyand | No | Nitro| *yes/no*
and so on| | |
Have you considered using a QTableWidget?
Yeah but
I want the same exact thing, but without rows
Or actually it would be a lot better with the List Widget but
With columns
That part you x'd out can be hidden easily.
table_widget.verticalHeader().setVisible(False)
Well okay, my whole idea is im making a lan chat, and it will have rooms. (kind of like teamspeak). And I have a square box where we will be able to see all rooms that are online. These rooms will have characteristics such as is the room private? How many ppl are in it and so on
Suppose I have a tkinter application. I have an authentication screen that sends a key to a server to check if its in the database. If the key is in the database, I destroy that window and load the main application. Otherwise, a prompt the user with an error on the auth page. I'm setting a global flag to True if the server response says the key is authenticated, destroy the auth window, and then check if the global flag is True and run the application. If the global flag is false, I don't run the main application's mainloop. Does this seem fine to you (so long as the source of the file is secure) ?
Seems fine as long as the requests in the main app are also authenticated
Otherwise someone can just decompile/reverse engineer your app and run the main app pretty easily
Well that's why I'm kind of banking on Pyarmor's security lol. And I decided to wrap the main app in a function that I call based off the json response @fathom crypt
Hmm obfuscation just means it'll take a bit longer to crack, there are also easier ways like sniffing network connections, then it's trivial to modify/send malicious requests
Why not use tokens? The initial auth with the key/secret can return a bearer that you have to send with all future requests. You'll have to keep track of these and expire them as required.