Qt widget stops receiving paintevents - qt

I have been doing an implementation of Conways game of life in PySide [source]. So far it works good until a point in which, under certain conditions I havent figured out yet, the QGraphicsView i use to display the grid (which consists of several QGraphicsRectItems on a QGraphicsScene) suddenly stops being painted continuously. The rest of the window remains responsive and the game thread keeps running and signaling for the ui to update the current generation number. It is only when the window gains focus that the graphicsView updates for about a second and then freezes again.
I find this behavior particularly strange given that i dont override paintEvent, nor call repaint/update methods at all, but what the game thread does is to update every RectItem's brush color according to the status it should have every generation.
Any ideas on what could be causing this?
btw this is on Kubuntu 14.04.3 / KWin 4.11.11 / Qt 4.8.6

Managed to solved it myself! In case someone runs into same issue, all that i needed to do was to schedule an update by calling the update method of the qgraphicsscene every generation (i.e. after operating on the graphicRects from the game thread).
I assume the strange behavior was probably the result of trying to save cpu load, since for the gui thread there was no work to be done!

Related

R tcltk responsive gui during calculation

Hello dear stack overflow community.
i'm currently working on an R project for statistical calculations that involves a gui and also time consuming heuristics. in the gui shall be an button to start and stop the calculation and a textfield that reports the best error so far.
so i'm stuck with the question how to keep the gui responsive during the calculation.
some example code
require("tcltk")
result<-tclVar("")
start<-function(){
active<<-TRUE
tkconfigure(button,text="stop",command=stop)
dostuff()
}
stop<-function(){
active<<-FALSE
tkconfigure(button,text="start",command=start)
}
dostuff<-function(){#this would be the optimization function
while(active){
tclvalue(result)<-#do some stuff
}
}
toplevel<-tktoplevel()
button<-tkbutton(toplevel,text="start",command=start)
entry<-tkentry(toplevel,textvariable=result)
tkpack(button)
tkpack(entry)
in the do stuff function some multithreading stuff seems to be necessary. its a requirement to work on windows and linux. i'm hoping for ideas how to archive this. thanks in advance
I think the easiest way is to start an R script as background process using system or system2 with the wait=FALSE parameter so that the long running calculation is processed in the background.
If you want to update the UI to show intermediate results or progress the R script must write the current state into an "exchange" file that can be used to update the UI.
To update the UI you have to check for the new state periodically e. g. by using the after command of Tcl/Tk, see:
http://www.tcl.tk/man/tcl/TclCmd/after.htm
For an example of starting an R script as background process see here:
http://stackoverflow.com/questions/14208976/r-run-source-in-background
Note that R is single threaded and updating the Tk-UI must be done from the same thread (process) that created the UI since the main event loop is running here.
Also take care that you shouldn't allow the user to make conflicting changes via the UI while the background task is running (e. g. starting another background task - except you want to support this).
Canceling the background process via the UI ("cancel button") can be done best by using another "signal file" that is checked by the background process periodically.

Coded UI execution is extremely slow than usual?

I have coded UI project with five UIMaps.One of the UIMap is very large and it covers several features of the testing application.suddenly the coded UI playback become so slow. I separate some features from the large UIMap into separate UIMaps. But still some of the test methods running very slower than usual.Is there any solutions to fix this issue?
You can use the below settings in your TestInitialize part and check whether this solves your purpose.As now we don’t need to add the annoying Sleep statements whenever a UI Control is busy and not ready to receive input.
By default, the engine checks the UI Thread (foreground thread) to determine if a control is ready.
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.Disabled;
By implementing this you can reduce the execution time.
I can not comment yet so here is an answer.
I had the same problem. see Coded ui Test fails at random times on server
waitforcontrolready was a solution next to PropertyExpressionOperator.Contains to search for a variable title. But also check the controlID of your control in your UIMap. It can change depending which windows are open on screen.
I remove them all unless I am 100% sure it stays the same.
I have figured it out after a search in the net, the class name of the main window is changed because of the latest releases. I have check the latest main window name and add it in the UIMap constructor as instructed in the following link Mathew Aniyan's Blog

Catching Qt modifier key releases

I'm a newcomer to Qt, but I'm trying to implement what basically amounts to a video-game-esque input loop in a Qt application (crazy, I know, but see if you can help). I need accurate, one-to-one event handling for key presses and key releases, for all keys, including modifiers, no matter how weirdly you chord-up the keyboard.
Of course, your main access to key events is through QKeyEvent. But let's say the following happens:
user presses and holds Ctrl
user presses and holds Up
user releases Ctrl and Up simultaneously
As far as I can tell, what I get from Qt is:
QKeyEvent for the pressing of Ctrl, by itself (Qt::Key_Ctrl)
QKeyEvent for the pressing of Up, by itself (Qt::Key_Up)
QKeyEvent for the releasing of Ctrl+Up, with key() == Qt::Key_Up and the Ctrl bit reflected in a modifier change.
This may be not exactly accurate, but it's my best guess as to what's going on from way too much debugging of the issue. In any event, the key release events when modifiers are involved are incredibly unreliable.
The Ctrl+Up sequence there at the end is the problem. Now, I know I'm getting modifier state in e->modifiers(), and I'm getting the key press in e->key(). I could do some complicated hacks, trying to remember the modifier state internally, to detect when the user's released the modifier. But then, the Qt docs inform me, speaking of e->modifiers(), that:
This function cannot always be trusted. The user can confuse it by pressing both Shift keys simultaneously and releasing one of them, for example.
This is exactly the case I'm trying to avoid.
Is there any reliable way to keep track of one-to-one key presses and releases, for both normal and modifier keys, in Qt? If not, what's the closest you can get?
EDIT: I can refine this a little bit. It seems that if you hold down Cmd on a Mac, press a few keys (letter keys, say), release them, then release Cmd, you don't get release events for the letter key releases. I'm going to try to isolate a small example and see if this is actually a Qt bug.
I think if you are getting very specific with the keyboard, you are going to have leave Qt and get something that is OS specific, or you need to handle the Qt events before any filtering happens.
Handle Qt Events Before Filtering
Accelerators in Qt look for and wait on Alt+__ combos and you can set up Ctrl+__ combos to be listened to by QAction.
Both of these types of Objects built into QApplication and the general GUI environment, might be interrupting the messages you are getting, and giving you less than what you are expecting.
Qt Documentation: The Event System ... this part has a link to this...
QCoreApplication::notify() ... which tells the highest level that a Qt Application can be written to handle input using the Qt API:
Installing an event filter on QCoreApplication::instance(). Such an event filter is able to process all events for all widgets, so it's just as powerful as reimplementing notify(); furthermore, it's possible to have more than one application-global event filter. Global event filters even see mouse events for disabled widgets. Note that application event filters are only called for objects that live in the main thread.
OS Specific Keyboard Handling Alternative
If looking at debug statements from a Qt event filter installed at the level mentioned above yields the same results as what you mentioned in your question, then you will need to go to the OS specific keyboard input stuff. For example in Windows you would need to scan the keyboard and or look at the VK state of the whole keyboard and do something with it (with something like GetKeyboardState() ).
I know it's a bit late to answer this question. Still... I have the same problem with Mac key release events and there is an open bug QTBUG-36839.
On Windows you may implement keyboard hook to catch every key presses/releases. But even that is not reliable in some cases. E.g. if you will type lock screen shortcut after unlocking you will NOT see any key release. I guess there must be something similar to hook on Mac. If it is important to you to remember what exactly physical key user pressed - I think this is one of the best ways. At the same time, from my experience, doing something low-level takes a lot of time and may bring a weird bugs in cases you never could imagine. So the question is: are you sure you cannot make what you need with something like QAction?
Or maybe you could just use Control instead of Command in your shortcuts :)

How to handle memory leaks?

I'm not that familiar to memory handling, but i am currently working on a Qt project (c++), developing an app for Symbian devices, using the Qt Nokia SDK.
Platform: Windows 7
1'st question:
If i create a pushbutton like this:
QPushButton *button = new QPushButton(parent);
Do i have to delete it? (I think no, since it is part of the UI, but correct me if i'm wrong).
2'nd question:
How can i find a memory leak, do you know of any good programs that can help me with this?
I've tried using Nokia Analyzer tool, but when i run atool:
atool.exe -lf build armv5 udeb -f phoneMeomoryLog
i just get
Build type: udeb Build platform: armv5 Data gathering mode: log to
file Allocation call stack size: 40 Free call stack size: 0 Deferred
free: feature disabled Heap corruption check (guard blocks): feature
disabled AnalyzeTool : Error, creating/reading makefiles.
Hope someone can answer me.
Thanks in advance
1'st question : No you don't have to delete it. It will be deleted when the parent is deleted. So you have to delete the parent which is probably a form or dialog.
When you create the dialog with Qt::WA_DeleteOnClose flag Qt deletes this widget when the widget has accepted the close event. So you will not have any memory leaks.
So create your dialog with this flag and add your widgets as you are doing now and you will be fine.
2'nd question: If you are running on linux use valgrind.
example : valgrind --tool=memcheck --leak-check=yes ./myprogramname
valgrind has many options you can use for fine tuning.
Also using *unique_ptr* or *auto_ptr* if you are using older c++ or QScopedPointer are good programming techniques to avoid memory leaks.
The answer to your first Q is No. It seems that unlike windows standard GUI Objects, in Qt you should not delete it. It is being released when your main window is being closed.
You can use microsoft's memory link detector embedded at VS. Find more in this link.
Both "It is being released when your main window is being closed." and "The parent just releases the UI resources, not the memory !!! – hsalimi " are wrong. The parent keeps a list of its children and will delete them when it is destructed itself. This has nothing to do with "UI resources" or "main window", it's normal QObject behaviour. std::auto_ptr is neither needed nor useful here either.
Well, I have no experience in Qt Nokia SDK, but based on my C++ knowledge.
Yes. Everything created by new should be later freed. A pointer cannot free itself and C++ doesn't offer any garbage collector.
There are several ways. For example, check how many new's you're doing and how many delete's. For each new there should be a delete somewhere. Check the memory used: if memory used only grows and never (or not often) decreases, then you're not handling memory correctly. Make sure you're deleting any allocated resources on destructors.
To avoid this you can use auto-pointers

Using a pyqt widget from a linearly running console application

My scenario here is the following: I am using a pyqt widget to display a solid color fullscreen on a second display and observe this display with a camera that is continuously capturing images. I do some processing with the images and this is the data I am interested in. This works great when used interactively with ipython and matplotlib using the qt4agg backend like so
% ipython -pylab
# ... import PatternDisplay, starting camera
pd = PatternDisplay(); pd.show(); pd.showColor(r=255,g=255,b=255)
imshow(cam.current_image)
I need a similar behavior now in a console script though: it should display the PatternDisplay widget, capture an image, than change the color on the PatternDisplay and take a new image and so on.
The problem is now that the PatternDisplay is never updated/redrawn in my script, likely because PyQt never gets a chance to run it's event queue. I had no luck trying to move the linear worker part of my script into a QThread because I cannot communicate with the PatternDisplay Widget from another Thread any longer. I tried to replicate the implementation of ipython/matplotlib, but I didn't fully understand it, it is quite complicated - it avoids running the QApplication main loop via monkey patching and somehow moves QT into it's own thread. It then checks periodically using a QTimer if a new command was entered by the user.
Isn't there an easy way to achieve what I want to do? I am gladly providing more information if needed. Thanks for any help!
What you need is easier than IPython's job - IPython makes the Qt application and the command line interactive at the same time.
I think the way to do it in Qt is to use a timer which fires at regular intervals, and connect the signal to the 'slot' representing your function that gets the new image and puts it in the widget. So you're pulling it in from the event loop, rather than trying to push it.
I've not used Qt much, so I can't give specifics, but the more I think about it, the more I think that's the right way to do it.
I solved the same problem (i.e. interactive ipython console in terminal, and GUI thread running independently) in the following way with ipython 0.10 (code here)
1. Construct QApplication object, but don't enter its event loop explicitly
2. Run the embedded IPython instance
3. Run the UI code you need by instantiating your window and calling show() on it (like here with the yade.qt.Controller(), which I aliased to F12. (I did not find a way how to ask the embedded shell to run a command at the start of the session, as if the user had typed it)
(You can also show() your window first, then run the embedded ipython. It will provide event loop for Qt.)
(BTW I also tried running Qt4 from a background thread (using both python threads module, and Qt4.QThreads), but it refuses to run in such way stubbornly. Don't bother going that way.)
The disadvantage is that UI will be blocked while ipython is busy. I hope to finding something better for 0.11, which should have much better threading facilities (I asked on ipython-users about how to unblock the UI).
HTH, v.

Resources