PyQt5 QTableView cell editing behaviour - superimposition of original value - qt

I'm messing around with tables in PyQt for the first time and am running into some unexpected behaviour when editing cell values.
Specifically when I type data, it appears over the top of the existing cell data (so if the cell originally had '123' in it, and I type '456', I end up with 2 lots of 3 characters, one over the top of the other - at least until I press enter).
Just to be clear, I have no issues with setData writing the changes to the model, or with the changes being reflected in the table after editing is complete - that's all happening fine. The only problem is seeing the original value and the new value I'm typing in occupying the same space until editing finishes.
So presumably what I want to do is alter my existing data method:
def data(self, index, int_role=None):
row = index.row()
column = index.column()
if int_role == QtCore.Qt.DisplayRole:
return str(self._data[row][column])
elif int_role == QtCore.Qt.EditRole:
return str(self._data[row][column])
else:
return None
so that it somehow recognizes if the cell it's being asked to provide data for (in DisplayRole mode) is currently being edited, and if so, return an empty string instead of the actual data (as the EditRole branch of the code is being called as well at the same time and is happily handling display duties until editing is finished).
I've had a look around the QT docs but cannot work out how to do this.
Edit: After ceppo's comments, I've looked at creating a new ItemDelegate - but looking into it further it looked like I would be able to instead switch out the itemEditorFactory in the existing one - specifically I added the following to my code:
newEditor = QLineEdit()
newEditor.setAutoFillBackground(True)
ief = QItemEditorFactory()
ief.registerEditor(QVariant.String, LineEditorCreator())
tableView.itemDelegate().setItemEditorFactory(ief)
with LineEditorCreator defined as follows:
class LineEditCreator(QItemEditorCreatorBase):
def __init__(self):
QItemEditorCreatorBase.__init__(self)
def createWidget(self, parent):
wdgt = QLineEdit(parent)
wdgt.setAutoFillBackground(True)
return wdgt
def valuePropertyName(self):
return "String"
however now I get a Segmentation fault as soon as I try to edit a cell value. Putting a print statement in as the first line in the createWidget statement shows it not ever getting executing - some print statements in the createWidget shows that the Segmentation faults occur even before the first line of createWidget executes (though the __ init __ method completes fine).
Ceppo also said that the behaviour I'm experiencing could be due to a bug (in Qt, PyQt or something else underlying) - I'll be replacing my current Ubuntu 15.10 installation with 16.04 soon so with some luck that will solve the issue entirely.

Upgrading ubuntu 15.10 to 16.04 did indeed fix the problem.
My 16.04 distro has python3-pyqt5 and other qt packages with versions all around 5.5.1 - I did check but didn't think to jot down the versions of those packages in my 15.10 installation before wiping it - but packages.ubuntu.com says 5.4.2 is the current version for 15.10 and that sounds familiar.
So if anyone else with QT 5.4.2 is running into the same thing, upgrading to 5.5.1 might be worth a try - either by upgrading to a newer distro or attempting to find and use a backport of the newer QT version.
Thanks Ceppo93, it was a good guess.

Related

How to avoid RuntimeError while call __dict__ on module?

it is appearing in some big modules like matplotlib. For example expression :
import importlib
obj = importlib.import_module('matplotlib')
obj_entries = obj.__dict__
Between runs len of obj_entries can vary. From 108 to 157 (expected) entries. Especially pyplot can be ignored like some another submodules.
it can work stable during manual debug mode with len computing statement after dict extraction. But in auto it dont work well.
such error occures:
RuntimeError: dictionary changed size during iteration
python-BaseException
using clear python 3.10 on windows. Version swap change nothing at all
during some attempts some interesting features was found.
use of repr is helpfull before dict initiation.
But if module transported between classes like variable more likely lazy-import happening? For now there is evidence that not all names showing when command line interpriter doing opposite - returning what expected. So this junk of code help bypass this bechavior...
Note: using pkgutil.iter_modules(some_path) to observe modules im internal for pkgutil ModuleInfo form.
import pkgutil, importlib
module_info : pkgutil.ModuleInfo
name = module_info.name
founder = module_info.module_finder
spec = founder.find_spec(name)
module_obj = importlib.util.module_from_spec(spec)
loader = module_obj.__loader__
loader.exec_module(module_obj)
still unfamilliar with interior of import mechanics so it will be helpfull to recive some links to more detail explanation (spot on)

How to get the 'execution count' of the most recent execution in IPython or a Jupyter notebook?

IPython and Jupyter notebooks keep track of an 'execution count'. This is e.g. shown in the prompts for input and output: In[...] and Out[...].
How can you get the latest execution count programmatically?
The variable Out cannot be used for this:
Out is a dictionary, with execution counts as keys, but only for those cells that yielded a result; note that not all (cell) executions need to yield a result (e.g. print(...)).
The variable In seems to be usable:
In is a list of all inputs; it seems that In[0] is always primed with an empty string, so that you can use the 1-based execution count as index.
However, when using len(In) - 1, in your code, you need to take into account that the execution count seems to be updated before execution of that new code. So, actually, it seems you need to use len(In) - 2 for the execution count of the most recent already completed execution.
Questions:
Is there a better way to get the current execution count?
Can you rely on the above observations (the 'seems')?
After more digging, I found the (surprisingly simple) answer:
from IPython import get_ipython
ipython = get_ipython()
... ipython.execution_count ...
This does not show up in the IPython documentation, though could (should?) have been mentioned here: https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.interactiveshell.html (I guess attributes are not documented). Here you do find run_line_magic (which was mentioned in a comment to my question).
The way I found this attribute is by defining ipython as above and then doing code completion (TAB) on ipython. (but it does not have documentation).
help(ipython)
gives you documentation about InteractiveShell, and it does mention execution_count (though it does not confirm its purpose):
| execution_count
| An int trait.

Qt error is printed on the console; how to see where it originates from?

I'm getting this on the console in a QML app:
QFont::setPointSizeF: Point size <= 0 (0.000000), must be greater than 0
The app is not crashing so I can't use the debugger to get a backtrace for the exception. How do I see where the error originates from?
If you know the function the warning occurs in (in this case, QFont::setPointSizeF()), you can put a breakpoint there. Following the stack trace will lead you to the code that calls that function.
If the warning doesn't include the name of the function and you have the source code available, use git grep with part of the warning to get an idea of where it comes from. This approach can be a bit of trial and error, as the code may span more than one line, etc, and so you might have to try different parts of the string.
If the warning doesn't include the name of the function, you don't have the source code available and/or you don't like the previous approach, use the QT_MESSAGE_PATTERN environment variable:
QT_MESSAGE_PATTERN="%{function}: %{message}"
For the full list of variables at your disposal, see the qSetMessagePattern() docs:
%{appname} - QCoreApplication::applicationName()
%{category} - Logging category
%{file} - Path to source file
%{function} - Function
%{line} - Line in source file
%{message} - The actual message
%{pid} - QCoreApplication::applicationPid()
%{threadid} - The system-wide ID of current thread (if it can be obtained)
%{qthreadptr} - A pointer to the current QThread (result of QThread::currentThread())
%{type} - "debug", "warning", "critical" or "fatal"
%{time process} - time of the message, in seconds since the process started (the token "process" is literal)
%{time boot} - the time of the message, in seconds since the system boot if that can be determined (the token "boot" is literal). If the time since boot could not be obtained, the output is indeterminate (see QElapsedTimer::msecsSinceReference()).
%{time [format]} - system time when the message occurred, formatted by passing the format to QDateTime::toString(). If the format is not specified, the format of Qt::ISODate is used.
%{backtrace [depth=N] [separator="..."]} - A backtrace with the number of frames specified by the optional depth parameter (defaults to 5), and separated by the optional separator parameter (defaults to "|"). This expansion is available only on some platforms (currently only platfoms using glibc). Names are only known for exported functions. If you want to see the name of every function in your application, use QMAKE_LFLAGS += -rdynamic. When reading backtraces, take into account that frames might be missing due to inlining or tail call optimization.
On an unrelated note, the %{time [format]} placeholder is quite useful to quickly "profile" code by qDebug()ing before and after it.
I think you can use qInstallMessageHandler (Qt5) or qInstallMsgHandler (Qt4) to specify a callback which will intercept all qDebug() / qInfo() / etc. messages (example code is in the link). Then you can just add a breakpoint in this callback function and get a nice callstack.
Aside from the obvious, searching your code for calls to setPointSize[F], you can try the following depending on your environment (which you didn't disclose):
If you have the debugging symbols of the Qt libs installed and are using a decent debugger, you can set a conditional breakpoint on the first line in QFont::setPointSizeF() with the condition set to pointSize <= 0. Even if conditional breakpoints don't work you should still be able to set one and step through every call until you've found the culprit.
On Linux there's the tool ltrace which displays all calls of a binary into shared libs, and I suppose there's something similar in the M$ VS toolbox. You can grep the output for calls to setPointSize directly, but of course this won't work for calls within the lib itself (which I guess could be the case when it handles the QML internally).

Why does Julia> (1,2,3) return (1,2,0)

I've been working through the Julia Tutorial, and strangely (1,2,3) returns (1,2,0).
(1,2,3,4) returns (1,2,0,0)
(1,2,3,4,5) returns (1,2,3,4,5) as expected.
It seems that sets of size 3 or 4 replace the 3rd and fourth elements with 0. I don't expect that this is normal behavior but I'm not familiar with the environment so I'm not sure with what I might have done to cause this.
I deleted all julia files from my profile and restarted the interpreter, and the behavior persists.
Version 0.3.5 (2015-01-08 22:33 UTC) under windows executed in cygwin.
Same problem when executed from command.
This is a (very strange!) long standing display bug on Windows. You can read about it at the link - in short, the value is correct but it doesn't display right. It should also be fixed in final release of Julia 0.4, which will use LLVM 3.5 (at least, thats what the thread says).

gotoAndStop(label) fails with error 2109

I have two movie clips:
mov1 has frames with labels in such sequence ("item"," btn", "win", "loose")
mov2 has frames with labels in such sequence (" ", "item", "win", "loose")
This is two standardized movie clips, which are ruled by one class MovItem.
In constructor of MovItem I init:
public function MovItem(item_mc:MovieClip )
{
this.item_mc.addEventListener( MouseEvent.CLICK, dispatchEvent );
//this.item_mc.gotoAndStop('btn');
this.item_mc.gotoAndStop(1);
}
In web version all works correctly, but in AIR 2.6 for Android it fails with error:
Error #2109: Frame label btw not found.
on gotoAndStop('btn'); on element which don't have such label.
And when I'm gotoAndStop(1); on this item all works fine.
All should be great, but 'btw' label on second movie clip is situated on second frame.
How can I fix it easily without total rework in .fla resources? Why does it works on web application, but on AIR fails? Thanx for you time.
This is actually happening in both the web version and the AIR version because mov2 has no frame called btn.
On the web version you will get a compiler warning but instead of quitting the application it just ignores the gotoAndStop(). However when compiling to AIR the compiler is in strict mode which converts compiler warnings to errors and won't allow you to compile until they are fixed.
It is bad practice anyway to call a function that you know is erronous (especially in a constructor method) so you should ether pass the frame to the constructor as a parameter (if they are going to different frame numbers) or explicitly give it the frame number e.g. gotoAndStop(2) (if they all go to the same frame number).
Also check you haven't misspelt the frame as you refer to the frame as both btn and btw in your question.

Resources