Re: [PyQt] Fwd: Re: c++ app integrate PyQt

2013-10-01 Thread Matt Newell

> 
> If you would forward an example to me it would very helpful.  I think
> both of you are suggesting that I wrap the C++ (BTW a very large app)
> and then write the entire program using PyQt. Is that correct. 


In reality you only need to wrap a very very small part of the API to make the 
app a python app.  Once the app is compiled as a library, which should require 
no changes at all(unless you are on windows then you'll need to add dllexport 
for any classes/functions used externally), the only difference being that your 
main isn't called implicitly.

Initially it can be as simple as wrapping a single function so your python 
"program" looks something like:

import myappaslib

if __name__ == "__main__":
myappaslib.main()


Where the .run function is the contents of your current main function.  Then 
as the need arises you can move stuff into python, such as the creations of the 
QApplication, loading of python functionality, etc.

However you shouldn't have any problems going the other route and embedding 
python in the app. I've done it for years now without issue.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Fwd: Re: c++ app integrate PyQt

2013-10-01 Thread Matt Newell
> 
> That sounds encouraging.  But it lacks a little detail - like how does
> one embed python (PyQt) into a C++ app.  The sip I sort of understand
> and it is doable.  I only need a few C++ classes and that makes sense.
> But I don't have a clue how or where to start on embeding PyQt.  Does
> someone have an example or a link explaining the details.
> 
> Johnf

The embedding is really not very involved.  Here is a snippet of code from one 
of my apps, with some irrelevant stuff removed.  This both initializes python, 
and loads CWD/plugins as a python module where you can load whatever you want 
from the __init__.py, including submodules.

Matt

// Return the named attribute object from the named module.
// Returns a NEW reference(PyObject_GetAttrString)
PyObject * getModuleAttr(const char *module, const char *attr)
{
#if PY_VERSION_HEX >= 0x0205
PyObject *mod = PyImport_ImportModule(module);
#else
PyObject *mod = PyImport_ImportModule(const_cast(module));
#endif

if (!mod)
{
PyErr_Print();
return 0;
}

#if PY_VERSION_HEX >= 0x0205
PyObject *obj = PyObject_GetAttrString(mod, attr);
#else
PyObject *obj = PyObject_GetAttrString(mod, const_cast(attr));
#endif

Py_DECREF(mod);

if (!obj)
{
PyErr_Print();
return 0;
}

return obj;
}

void loadPythonPlugins()
{

Py_Initialize();
PyEval_InitThreads();

PyObject * sys_path = getModuleAttr("sys", "path");

if (!sys_path) {
LOG_1( "Python Initialization Failure: Failed to get sys.path" 
);
return;
}

QString dir = QDir::currentPath();

// Convert the directory to a Python object with native separators.
#if QT_VERSION >= 0x040200
dir = QDir::toNativeSeparators(dir);
#else
dir = QDir::convertSeparators(dir);
#endif

#if PY_MAJOR_VERSION >= 3
// This is a copy of qpycore_PyObject_FromQString().

PyObject *dobj = PyUnicode_FromUnicode(0, dir.length());

if (!dobj)
{
PyErr_Print();
return;
}

Py_UNICODE *pyu = PyUnicode_AS_UNICODE(dobj);

for (int i = 0; i < dir.length(); ++i)
*pyu++ = dir.at(i).unicode();
#else
PyObject *dobj = PyString_FromString(dir.toAscii().constData());

if (!dobj)
{
PyErr_Print();
return;
}
#endif

// Add the directory to sys.path.
int rc = PyList_Append(sys_path, dobj);
Py_DECREF(dobj);
Py_DECREF(sys_path);

if (rc < 0)
{
PyErr_Print();
return;
}

PyObject *plug_mod = PyImport_ImportModule("plugins");
if (!plug_mod)
{
PyErr_Print();
return;
}
Py_DECREF(plug_mod);

PyEval_SaveThread();
}
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] c++ app integrate PyQt

2013-09-30 Thread Matt Newell
On Monday, September 30, 2013 04:51:24 PM John Fabiani wrote:
> Hi,
> I have an existing Qt C++ app (Qt5.1.1).  Is it possible to integrate
> PyQt into the project.  I'd like the PyQt to have access to some of the
> C++ functions, C++ classes, but I want to write frames,windows, all the
> controls in PyQt including accessing the database.  Most important I
> want only one app loop.  I was able in get PythonQt working but realized
> that it was a lot of work to get it to do what I want - that is to
> create a complete sub-program written in python.
> 
> 
> Any hints or links will be helpful.
> 
> Thankis in advance,
> 
> 
> Johnf


Yes it's possible.  You have to wrap any c++ classes you want to use from 
python using sip.  Then you need to embed python in your app, or rewrite the 
main part of the application in python.

You'll want to first split your app into a library so you can test your python 
bindings from a regular python script or cmd interpreter.  Start with one 
class to get your feet wet and go from there.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Using SWIG to wrap application written in QT

2013-08-28 Thread Matt Newell
On Wednesday, August 28, 2013 01:01:43 PM Kenneth Miller wrote:
> ping. :)
> 
> 
> 
>  From: Kenneth Miller 
> To: "pyqt@riverbankcomputing.com" 
> Sent: Monday, August 26, 2013 5:25 PM
> Subject: Using SWIG to wrap application written in QT
> 
> 
> 
> So I have this application that I'm writing that uses the Qt libraries. I
> want to wrap the my application and all of it's objects so that I can call
> it from a scripting language quickly, be it python, or ocaml or whatever.
> Anyway, for the last bit I've been trying to get a module compiled that
> will allow me to dynamically call into the classes & functions that I've
> defined. SWIG seems to work right, and recently I even got my own self
> defined class within a module from my C++ source to run, although it
> segfaulted and I have yet to find out exactly why. 
> 
> 
> 
> Can this be done? I mean, I was wondering it would be more appropriate that
> I use SIP. One of the problems that I'm facing (I think) is that some
> arguments to my classes and functions are Qt objects. But I can't export
> those functions in my SWIG module without also writing a wrapper to the Qt
> objects manually (is that right?). I'm very new to SWIG, but I definitely
> need the speed of a scripting language for my development, because the
> compile cycle with Qt and C++ is slow. In addition, I'm kind of
> considering SIP in parallel, so I need advice as to which is more
> appropriate. 
> 
> Can anybody advise me what the best route is in order to get what I want?
> SIP or SWIG?


You'll definitely want to use sip.  PyQt sources(check the sip dir) themselves 
are a good reference on how to do things.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QString API v2 concern...

2013-05-09 Thread Matt Newell
On Thursday, May 09, 2013 12:40:13 PM you wrote:
> Hi Matt,
> 
> I'm in no position to comment on your wider point, but...
> > 
> FWIW, the Python-uses-roughly-utf16 meme is a common oversimplification.
> First, as I'm sure most people know, there are significant changes between
> Python2 str/unicode and Python3 str. That cannot but be reflected in
> differences between the CPython usage across the 2/3 boundary.
> 
> What is less well known is that there is a significant change to CPython
> between 3.2 and 3.3 where the latter can store a str as either an array of
> 8, 16 or 32 bit values with automatic run-time conversions between them
> (and API changes to match). So whatever else happens within PyQt, I don't
> think the aspiration to the old 1-copy model can be relied on. In the
> event, this is what I came up with for the QString to str direction
> (corrections/optimisations welcome!):
> 
> 
> PyObject *Python::unicode(const QString &string){#if PY_MAJOR_VERSION < 3
> /* Python 2.x. http://docs.python.org/2/c-api/unicode.html */
> PyObject *s = PyString_FromString(PQ(string));
> PyObject *u = PyUnicode_FromEncodedObject(s, "utf-8", "strict");
> Py_DECREF(s);
> return u;#elif PY_MINOR_VERSION < 3
> /* Python 3.2 or less.
> http://docs.python.org/3.2/c-api/unicode.html#unicode-objects */#ifdef
> Py_UNICODE_WIDE
> return PyUnicode_DecodeUTF16((const char *)string.constData(),
> string.length() * 2, 0, 0);#else
> return PyUnicode_FromUnicode(string.constData(),
> string.length());#endif#else /* Python 3.3 or greater.
> http://docs.python.org/3.3/c-api/unicode.html#unicode-objects */
> return PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND,
> string.constData(), string.length());#endif}
> 
> 
> The referenced URLs contain more material.
> 
> Hth, Shaheed
> 

Interesting.  Thanks for the info.  Looking at the python source code for 
3.3.1 it looks like python will scan the string and either convert to 8-bit 
data if all the data falls in the latin1 range, or do a direct copy.  That 
means the situation is probably a bit worse wrt cpu usage, and a bit better 
wrt memory, at least in the common case.

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] QString API v2 concern...

2013-05-09 Thread Matt Newell
On Monday, May 06, 2013 07:49:25 AM Phil Thompson wrote:
> The first PyQt5 snapshots are now available. You will need the current SIP
> snapshot. PyQt5 can be installed alongside PyQt4.
> 
> I welcome any suggestions for additional changes - as PyQt5 is not
> intended to be compatible with PyQt4 it is an opportunity to fix and
> improve things.
> 
> Current changes from PyQt4:
> 
> - Versions of Python earlier than v2.6 are not supported.
> 
> - PyQt4 supported a number of different API versions (QString, QVariant
> etc.). PyQt5 only implements v2 of those APIs for all versions of Python.
> 

I haven't looked into this deeper but I am a bit worried about the possible 
performance impacts of QString always being converted to a python str/unicode. 
(Not to mention the added porting work when going c++ <-> python).

The vast majority of the PyQt code that we use loads data from libraries that 
deal with Qt types, and either directly loads that data into widgets, or does 
some processing then loads the data into widgets.  I suspect that this kind of 
usage is very common.  

As an example a user of QtSql with the qsqlpsql driver that loads data and 
displays it in a list view is going to see the following data 
transformations/copies:

PyQt4 with v1 QString api:

libpq data comes from socket
-> QString (probable utf8->utf16)
-> PyQt wrapper of QString (actual data not copied or converted)
-> QString (pointer dereference to get Qt type)

PyQt5, PyQt4 with v2 QString api:

libpq data comes from socket
-> QString (probable utf8->utf16)
-> unicode (deep copy of data)
-> QString (deep copy of data)

So instead of one conversion we now have one conversion and two deep copies.  
Another very probable side-effect is that in many cases either the original 
QString and/or the unicode object will be held in memory, resulting in two or 
possibly even three copies of the data.  Even if all but the last stage is 
freed, there will still be 2 or 3 copies in memory during processing depending 
on how the code is written, which can reduce performance quite a bit depending 
on data size because of cpu cache flushing.

So far this is completely theoretical, and I'm sure in a large portion of 
applications will have no noticeable effect, however I don't like the idea that 
things may get permanently less efficient for apps that do process and display 
larger data sets.

The one thing that stands out to me as possibly being a saving grace is the 
fact that (at least in my understanding) both Qt and python use utf16 as their 
internal string format, which means fast copies instead of slower conversions, 
and that it may be possible with some future Qt/python changes to actually 
allow QString -> unicode -> QString without any data copies.

At some point I will try to do some benchmarks and look into the actual code 
to see if there is an elegant solution to this potential problem.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Wrap with SIP in-out string parameters in class method

2012-12-11 Thread Matt Newell
On Tuesday, December 11, 2012 02:56:51 AM Alexander Bruy wrote:
> Hi all,
> 
> I'm new to SIP and have some troubles with wrapping class in SIP.
> I need to declare some parameters as in and out.
> 
> Here is class header
> 
> class AuthData
> {
>   public:
> virtual ~AuthData();
> bool get( QString dbName, QString &username, QString &password,
> QString message = QString::null );
> void put( QString dbName, QString username, QString password );
> static AuthData *instance();
>   protected:
> virtual bool request( QString dbName, QString &username, QString
> &password, QString message = QString::null ) = 0;
> void setInstance( AuthData *theInstance );
>   private:
> QMap< QString, QPair > mAuthCache;
> static AuthData *smInstance;
> };
> 
> And here is my sip file
> 
> class AuthData
> {
> %TypeHeaderCode
> #include 
> %End
> 
>   public:
> virtual ~AuthData();
> bool get( QString dbName, QString &username /In,Out/, QString
> &password /In,Out/, QString message = QString::null );
> void put( QString dbName, QString username, QString password );
> static AuthData *instance();
> 
>   protected:
> virtual bool request( QString dbName, QString &username /In,Out/,
> QString &password /In,Out/, QString message = QString::null ) = 0;
> void setInstance( QgsCredentials *theInstance );
> };
> 

You need to add the /Transfer/ annotation so that c++
has ownership and subsequent calls to instance() return a valid instance.

void setInstance( AuthData * theInstance /Transfer/ ); 

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Shortening multiple widget initializations to one line

2012-12-10 Thread Matt Newell
On Sunday, December 09, 2012 11:48:18 PM Shriramana Sharma wrote:
> Hi -- recently I was trying to shorten the following overly verbose
> (IMO) lines to:
> 
>   self . p1xSpin = QSpinBox ()
>   self . p1ySpin = QSpinBox ()
>   self . c1xSpin = QSpinBox ()
>   self . c1ySpin = QSpinBox ()
>   self . c2xSpin = QSpinBox ()
>   self . c2ySpin = QSpinBox ()
>   self . p2xSpin = QSpinBox ()
>   self . p2ySpin = QSpinBox ()
> 
> to:
> 
>   self . p1xSpin, self . p1ySpin, self . c1xSpin, self . c1ySpin,
>   self . c2xSpin, self . c2ySpin, self . p2xSpin, self . p2ySpin,
>   self . pHxSpin, self . pHySpin = ( QSpinBox () for i in range ( 
> 10 ) 
)
> 
> but I got the error:
> 
> Traceback (most recent call last):
>   File "./bezierview-cubic-interp.py", line 327, in 
> mainWindow = MainWindow ()
>   File "./bezierview-cubic-interp.py", line 204, in __init__
> self . p1xSpin, self . p1ySpin, self . c1xSpin, self . c1ySpin,
> AttributeError: 'MainWindow' object has no attribute 'p1xSpin'
> 

Probably some simple error here causing the line to try to get the attribute 
instead of set it.

>>> class Y(object):
>>> 
>>> 
>>>   
... def __init__(self):
... self.a, self.b = (QSpinBox() for a in range(2))
... 


  
>>> 
>>> 
>>> 
>>>   
>>> y = Y() 
>>> 
>>> 
>>>   

> Why is this, and is there any other method I can follow to shorten the
> tortuous list of repetitive commands for initializing multiple
> widgets?
> 

If you have a bunch of similarly named attributes then you can easily generate 
them.

>>> class X(object):
... def __init__(self):
... for at in ['%s%s%s' % (a,b,c) for a in ('c','p') for b in 
('x','y') for c in (1,2)]:
... setattr(self,at,QSpinBox())
... 
>>> x = X()
>>> x.cx1

>>> x.cx2
  


  


Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] Fix for /HoldGIL/ functions with exceptions enabled.

2012-11-06 Thread Matt Newell

The generateCatch/generateCatchBlock functions weren't taking into account the 
function specific HoldGIL setting, resulting in a compile error:

 error: ‘_save’ was not declared in this scope

This simple patch fixes the problem.

Matt
diff -r 76a18a32f759 sipgen/gencode.c
--- a/sipgen/gencode.c	Sat Sep 29 12:26:43 2012 +0100
+++ b/sipgen/gencode.c	Tue Nov 06 14:33:01 2012 -0800
@@ -203,9 +203,9 @@
 int secCall, FILE *fp);
 static void generateTry(throwArgs *, FILE *);
 static void generateCatch(throwArgs *ta, signatureDef *sd, moduleDef *mod,
-FILE *fp);
+FILE *fp, int rgil);
 static void generateCatchBlock(moduleDef *mod, exceptionDef *xd,
-signatureDef *sd, FILE *fp);
+signatureDef *sd, FILE *fp, int rgil);
 static void generateThrowSpecifier(throwArgs *, FILE *);
 static void generateSlot(moduleDef *mod, classDef *cd, enumDef *ed,
 memberDef *md, FILE *fp);
@@ -10578,7 +10578,7 @@
  * Generate the catch blocks for a call.
  */
 static void generateCatch(throwArgs *ta, signatureDef *sd, moduleDef *mod,
-FILE *fp)
+FILE *fp, int rgil)
 {
 /*
  * Generate the block if there was no throw specifier, or a non-empty
@@ -10595,11 +10595,11 @@
 int a;
 
 for (a = 0; a < ta->nrArgs; ++a)
-generateCatchBlock(mod, ta->args[a], sd, fp);
+generateCatchBlock(mod, ta->args[a], sd, fp, rgil);
 }
 else if (mod->defexception != NULL)
 {
-generateCatchBlock(mod, mod->defexception, sd, fp);
+generateCatchBlock(mod, mod->defexception, sd, fp, rgil);
 }
 
 prcode(fp,
@@ -10607,7 +10607,7 @@
 "{\n"
 );
 
-if (release_gil)
+if (rgil)
 prcode(fp,
 "Py_BLOCK_THREADS\n"
 "\n"
@@ -10629,7 +10629,7 @@
  * Generate a single catch block.
  */
 static void generateCatchBlock(moduleDef *mod, exceptionDef *xd,
-signatureDef *sd, FILE *fp)
+signatureDef *sd, FILE *fp, int rgil)
 {
 scopedNameDef *ename = xd->iff->fqcname;
 
@@ -10638,7 +10638,7 @@
 "{\n"
 ,ename,(xd->cd != NULL || usedInCode(xd->raisecode, "sipExceptionRef")) ? "sipExceptionRef" : "");
 
-if (release_gil)
+if (rgil)
 prcode(fp,
 "\n"
 "Py_BLOCK_THREADS\n"
@@ -10774,7 +10774,7 @@
 prcode(fp,");\n"
 );
 
-generateCatch(ct->exceptions, &ct->pysig, mod, fp);
+generateCatch(ct->exceptions, &ct->pysig, mod, fp, rgil);
 
 if (rgil)
 prcode(fp,
@@ -12252,7 +12252,7 @@
 prcode(fp,";\n"
 );
 
-generateCatch(od->exceptions, &od->pysig, mod, fp);
+generateCatch(od->exceptions, &od->pysig, mod, fp, rgil);
 
 if (rgil)
 prcode(fp,
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Re: [PyQt] QImage in BI24 format

2012-09-19 Thread Matt Newell
On Wednesday, September 19, 2012 12:19:31 AM Gelonida N wrote:
> On 09/18/2012 08:13 PM, Gelonida N wrote:
> > Hi,
> > 
> > I have a C-library creating an image supposedly in in BI24 format (video
> > application)
> > 
> > Now I'd like to display the image.
> > 
> > I tried to set the pixel format to QImage.Format_RGB888
> > 
> > and I can see the image.
> > However the red and blue colors are inversed.
> > 
> > Is there another format, that can directly display the image?
> 
> I managed to convice the other application to create the images in RGB32
> So for the time being my problem is solved.
> 
> However I would still be interested to know, whether Qt can support the
> fourc 'BI24' format and if not, how one could convert most efficiently.
> 

Any conversion is going to need to be implemented in C++ for best speed.

If you are looking for very high performance then you can use an opengl view 
to display the image and use one of the various shader languages to do 
anything you want with the texture(image) data, swapping two color components 
is especially easy once the plumbing is done to get a working view with 
shaders. That way no conversion is necessary on the main CPU.  If you do it 
this way you can upload the image data to an opengl texture without ever 
copying it into a QImage.  This is most likely going to require C++, though it 
may be possible from pure python with some combination of non-PyQt bindings 
and/or ctypes.

If you need the data in a QImage or an OpenGL view is not out of the question 
for whatever reason you can write your own QImageIO plugin that does the 
conversion while copying the data into the QImage, this avoids iterating 
through the image data more than once. This will have to be done in C++.

The next best way is to simply use a loop to iterate through the pixels and 
use qRgb/qRgba to get and set the values.  This is by far the easiest and is 
most likely plenty fast for most applications on modern computers.  Of course 
it will be quite a bit slower if implemented in python compared to C++.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] sip: extend exception support

2012-08-27 Thread Matt Newell

> 
> In current hg...
> 
> %VirtualErrorCode is a new sub-directive of the %Module directive.
> 
> all_throw_cpp_exception replaced by all_use_VirtualErrorCode.
> 
> /ThrowsCppException/ replaced by /UsesVirtualErrorCode/.
> 
> /NoThrowsCppException/ replaced by /NoUsesVirtualErrorCode/.
> 
> Removed SIPPyException.
> 
> Phil
> ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt

I'm coming in a bit late to this discussion, but I have been maintaining a 
similar patch for a few years in order to solve the same problem.  

Below is the documentation that I wrote for my patch.

I don't know enough about the code you just added to compare the approaches, 
but hopefully you can read through these docs(i can try to prepare an actual 
patch too if you want) and verify that your changes will allow the same level 
of functionality.  Specifically my code gives access to the c++ and python 
objects which allows the error to be handled without throwing a c++ exception, 
since in my case the calling c++ code does not expect an exception.

Under Sip Directives:

%VirtualErrorHandler


.. parsed-literal::

%VirtualErrorHandler *name*


Used to define the name of an error handler function that is called when the 
python reimplementation of
a virtual function throws an exception. The call to the virtual error handler 
is inserted in the
 `generated derived classes`_ to handle the exception before returning.

%VirtualErrorHandler defines a module-wide default virtual error handler 
function. One can specify virtual
error handler functions per class or per virtual function by using an 
annotation.

The named function must take two arguments. This first is the class instance. 
Generic virtual error handler
functions can simply use 'const void *' to accept all class types. The second 
argument is the const sipWrapper *
which can be cast to a PyObject *. These can be used to gather relevant 
debugging information, or to handle the
exception more intelligently by calling an error handler function on the c++ 
instance or the python instance.

The virtual error handler is responsible for clearing the exception before 
returning.

For example::

%ModuleHeaderCode
void MyVirtualErrorHandler( const void *, const sipWrapper * );
%End

%ModuleCode
void MyVirtualErrorHandler( const void * /*klass*/, const sipWrapper * 
/*pyObject*/ )
{
  PyErr_Print();
}
%End

%VirtualErrorHandler MyVirtualErrorHandler


Under Class Annotations:

VirtualErrorHandler
***

This annotation specifies the name of the default virtual error handler for the
class.

And under function annotations:

VirtualErrorHandler
***

This annotation specifies a virtual error handler for this function.
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] creating a variable number of widget

2012-07-02 Thread Matt Newell
On Sunday, July 01, 2012 04:09:31 PM David Beck wrote:
> I am trying to create a GUI for managing a multilingual lexical database.
> Every word in the database can have 1 to n meanings or senses, each of
> which has to have several types of information associated with it. This
> corresponds to a (simplified) XML structure as follows
> 
> 
>   word
>   
>   English definition
>   Spanish definition
>   example sentences
>   
>… etc., may be iterated many times
> 
> 
> What I would like to do is write a script that reads from the XML, counts
> the number of iterations of , and if there is more than one creates a
> QTabWidget for each  element with QGroupBoxes and QTextEdits to
> display the contents of each of the subelements. It doesn't seem possible
> to completely automate this process using some sort of loop (repeat for
> the number of  elements in ) because the constructors for the
> widgets are like this
> 
> Fieldbook.ui.tab = QtGui.QWidget()
> Fieldbook.ui.lL1Box = QtGui.QGroupBox(Fieldbook.ui.tab)
> Fieldbook.ui.lL1Definition = QtGui.QTextEdit(Fieldbook.ui.lL1Box)
> Fieldbook.ui.lL2Box = QtGui.QGroupBox(Fieldbook.ui.tab)
> Fieldbook.ui.lL2Definition = QtGui.QTextEdit(Fieldbook.ui.lL2Box)
> Fieldbook.ui.lExampleBox = QtGui.QGroupBox(Fieldbook.ui.tab)
> Fieldbook.ui.lExamples = QtGui.QTextEdit(Fieldbook.ui.lExampleBox)
> 
> On the first iteration this is fine, but the second iteration of the loop
> is going to create widgets with exactly the same names. Is there someway
> to replace something like the ".tab" in Fieldbook.ui.tab = QtGui.QWidget()
> with a variable that changes with every iteration of the loop?
> 
There's many ways to do this in python.  You could store each set of widgets 
in a tuple, and have a list of tuples, one for each Def.

widgetGroups = []
for def in defs:
tab = QtGui.QWidget()
IL1Box = QtGui.QGroupBox(tab)
...
widgetGroups.append( (tab,IL1Box,...) )


If you want to be able to reference the individual widgets by name instead of 
their index in the tuple, you could instead use a dict, or go one step further 
and use a class.

If for some reason you really wanted to store each widget individually in 
Fieldbook.ui's class dict, you could do

for def, i in enumerate(defs):
Fieldbook.ui.setattr( 'tab%i' % i, QtGui.QWidget() )
...

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Oci Sqldrivers support

2012-06-27 Thread Matt Newell
On Wednesday, June 27, 2012 09:56:46 AM Julian Ramos Marrero wrote:
> Hi,
> 
> One  question, Pyqt  support OCI driver? , for ORACLE database.
> 
> 
> Regards,
> 
> Jdarknet

Any QtSql driver should work with PyQt.

The QtSql drivers don't expose any API, it's all done through the generic 
QtSql api(QSqlDatabase,QSqlQuery, etc), so there is no need to provide python 
bindings for the drivers themselves.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] pyqt4, qt4 and stylesheets

2012-04-09 Thread Matt Newell
On Monday, April 09, 2012 02:21:37 PM José M. Rodriguez Bacallao wrote:
> no one?
> 
> On 4/9/12, José M. Rodriguez Bacallao  wrote:
> > hi folks, I am developing an application with  pyqt4. I am trying to
> > achieve the same look in all platform using stylesheets, for axample,
> > I need that my toolbar look the same (with a background image
> > repeating in x direction) in gnome, kde, xfce, windows and mac but
> > right now I am facing a problem, when I start my application under,
> > for example, XFCE using greybird as gtk 2/3 style, my toolbar is using
> > the background from greybird theme, not from my stylesheet and when
> > staring from kde 4.8, the dockwidgets are using some hints from the
> > current kde style. So, my question is: how to achieve the same look in
> > all platforms?
> 
> ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt

This question is more Qt oriented and this list is fairly low traffic. You 
might 
get a response but I would ask some of the Qt specific forums/lists as they 
have a wider audience and likely a lot more people with stylesheet experience.  
I personally have never used any of the stylesheet features with qt.

To be clear I'm not at all saying the question doesn't belong here, just that 
because it doesn't relate to the python bindings themselves there's no reason 
to not ask elsewhere also.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Re: [PyQt] Resizing window to smartly fit the contents

2011-11-24 Thread Matt Newell
On Thursday, November 24, 2011 09:49:51 AM Tom Bennett wrote:
> Hi Tayfun,
> 
> On Thu, Nov 24, 2011 at 2:26 AM, Tayfun Kayhan 
wrote:
> > Let *self.win* be your widget, then *self.win.sizeHint()* returns the
> > ideal or recommended size of your widget.
> > *self.win.minimumSizeHint()* returns the minimum recommended size. you
> > can set these to resize your widget.
> > 
> >   --
> > 
> > *From:* Tom Bennett 
> > *To:* pyqt@riverbankcomputing.com
> > *Sent:* Thursday, November 24, 2011 9:43 AM
> > *Subject:* [PyQt] Resizing window to smartly fit the contents
> > 
> > Hi,
> > 
> > I have a window that contains a composite widget that in turn contains
> > some basic widgets and a table view. Depending on different situations,
> > the table view can have a little or a lot data.
> > 
> > What I want is for the window to show a reasonable default size when it
> > comes up. In other words, when there is a little data, don't show a huge
> > window; when there is a lot of data, don't show a tiny window.
> > 
> > To make things more complicated, there has to be some minimum and maximum
> > size. For example, the window size cannot be bigger than the screen size.
> > But using the screen size is not exactly right, because the desktop
> > system occupies part of the screen. For example, on Windows, the bottom
> > area of the main screen is reserved for the system task bar, and should
> > not be covered by my window, whereas on the second screen usuallt one
> > can occupy the whole screen size.
> > 
> > I am wondering wat can be done to achieve this.
> > 
> > Thanks,
> > Tom
> > 
> > ___
> > PyQt mailing listPyQt@riverbankcomputing.com
> > http://www.riverbankcomputing.com/mailman/listinfo/pyqt
> 
> This does not fully solve my problem. sizeHint() and minimumSizeHint() do
> not take into account how many contents are in QTableView.
> 
> Thanks,
> Tom

Subclass QTableView and provide a sizeHint() that takes into account the 
actual content.   All it takes is iterating through the rows and columns, 
though you'll probably want to break the loop at some point after getting to 
some maximum.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Using PostgreSQL

2011-10-17 Thread Matt Newell

Before starting you app set the QT_DEBUG_PLUGINS environment var.

set QT_DEBUG_PLUGINS=1

Also in the windows registry Qt caches which plugins are valid.  If the 
qsqlpsql4.dll wouldn't load once it will not try to load it again even if you 
fix dll problems.  Go ahead and delete the entire plugin cache part of the 
registry each time.  You can automate this by creating a .reg file with the 
following contents adjusted for Qt version:

"""
Windows Registry Editor Version 5.00

[-HKEY_CURRENT_USER\SOFTWARE\Trolltech\OrganizationDefaults\Qt Plugin Cache 
4.6.false]

"""

Then you can execute the file with

regedit /s path_to_my.reg

The MSVCR90.dll might not actually be a problem, but you should be able to find 
out with the QT_DEBUG_PLUGINS env variable set.  You can also profile your app 
through depends.exe and see if qsqlpsql4.dll loads okay.

Matt


On Monday, October 17, 2011 03:06:34 AM pa...@paolodestefani.it wrote:
> Hello
> I have a problem using PostgreSQL with pyqt. My pc is a Windows 7 32bit,
> i've installed postgresql 9.1 with odbc drivers BUT i want to use it in
> pyqt with the native driver. I've wrote a small script to test everything
> but this work if i use ODBC, if i use PSQL i get an errore "Driver not
> loaded".
> This is the code:
> 
> app = QCoreApplication(sys.argv)
> db = QSqlDatabase.addDatabase("QPSQL")
> db.setHostName('localhost')
> db.setPort(5432)
> db.setDatabaseName('TestDB')
> db.setUserName('postgres')
> db.setPassword('*')
> if db.isOpen():
> db.close()
> if not db.open():
> raise Exception("Error opening database:
> {0}".format(db.lastError().text()))
> query = QSqlQuery()
> query.exec_("select * from test_table;")
> while query.next():
> print(query.value(0), query.value(1) )
> 
> This code return the error "Driver not loaded". If i change only the
> database driver, this line:
> 
> db = QSqlDatabase.addDatabase("QODBC")
> 
> I get the correct output:
> 
> 1 Prova paolo
> 2 Prova Pippo Baudo
> 
> So what's wrong ?
> 
> I've cheked qsqlpsql4.dll with dependecy walker and i get this log:
> 
> Error: At least one required implicit or forwarded dependency was not
> found.
> Error: At least one module has an unresolved import due to a missing
> export function in an implicitly dependent module.
> Warning: At least one module has an unresolved import due to a missing
> export function in a delay-load dependent module.
> 
> The missing librery should be MSVCR90.DLL but even if i dowload this file
> from internet i get the same error.
> I've tryed to install Microsoft Visual C++ 2010 runtime (vcredist_x86.exe)
> with no success.
> 
> 
> 
> ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Running Python scripts from a SIP-wrapped library

2011-07-30 Thread Matt Newell
On Saturday 30 July 2011 13:33:55 Jens Thoms Toerring wrote:
> Hi,
> 
>I guess this isn't the best place to ask but I haven't
> found anything really fitting yet. So, please, if this is
> too off-topic don't hesitate to redirect me to a better
> place (a "RTFM" is also going to be appreciated as long
> as it comes with a pointer to the relevant "M";-).
> 
> In short, I have a C++ library that has a SIP wrapper, so
> it can be used from both Python and C++. Within the library
> it should be possible to execute "modules", i.e. Python
> scripts, using the Python C-API. Those "modules" also need
> to 'import' the SIP-wrapper for the library.
> 
> I got this working using the following approach: In the
> code that runs a Python "module" I check first if Python
> is already running (that would be the case when the li-
> brary is used from Python via the SIP-wrapper) by testing
> with Py_IsInitialized(). If that isn't the case I call
> PyInitialize(). On the other hand, when it's true I start
> a new Python interpreter, using Py_NewInterpreter()
> (creating a new interpreter seems to be necessary since
> otherwise Python crashes somewhere in its innards with
> a segmentation fault once I call PyImport_Import() on
> the Python module to be executed). Once the "module" is
> done I stop the new interpreter with Py_EndInterpreter()
> (if one was started) or just call PyFinalize().
> 
>   All this seems to work fine when the Python script
> using my library is started from the command line. But
> now someone wanted to use spyder
> 
>   http://packages.python.org/spyder/
> 
> And if the Python script is run from spyder all kinds of
> weired things happen. In some cases the script simply seems
> to hang (one place seems to be the call of Py_NewInterpre-
> ter() as far as I can tell at the moment - I haven't found
> a good way to run spyder under a debugger and then getting
> at the place where things happen) or it aborts with one
> of several error messages about 'tstate mixup' and similar
> when the module has been run and the interpreter is removed.
> 
> I have been googling and trying to understand the docu-
> mentation I found for several days now and am still com-
> pletely confused. I haven't found some really coherent
> description what all this stuff what the GIL and Thread-
> States are all about and how far that could be at the
> heart of my problems. The C-API reference documentation
> is nice as far as it goes, but it's mainly a description
> of a lot of functions with not enough background informa-
> tion for me to help me figure out what actually is going
> wrong.
> 
> Perhaps someone with more knowledge about the details of
> Python and interfacing with C/C++ can tell me either that
> my whole approach is completely idiotic or, if it's not
> that bad, can give me some hints where I'm going wrong
> - or at least has some tips for things I should read and
> try to understand...
>Thanks and best regards, Jens


My quick guess is that you should not be calling Py_NewInterpreter, but 
instead wrap your calls into python code with

SIP_BLOCK_THREADS
// Call python functions
SIP_UNBLOCK_THREADS

These are just macros for calling PyGILState_Ensure/PyGILState_Release, so you 
can call them directly if you aren't doing this inside a sip module.

#define SIP_BLOCK_THREADS   {PyGILState_STATE sipGIL = PyGILState_Ensure();
#define SIP_UNBLOCK_THREADS PyGILState_Release(sipGIL);}


Matt


___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Building SIP project

2011-07-05 Thread Matt Newell
On Tuesday 05 July 2011 10:19:08 Jens Thoms Toerring wrote:
> Hi,
> 
>I have a SIP wrapper for a C++ library, consisting of
> about 60 .sip files. Things work quite well, but I have
> an issue with the process of creating the wrapper library.
> I use an (a bit adapted) configure script like it is shown
> in the documentation.
> 
> The problem is that each small change to any of the .sip
> files requires a rebuilt of each and every file. I have
> a "central" .sip file that includes all the others. And
> when I change any of those files and thus need to run
> the configure script all .cpp files are created anew.
> And then, of course, they're newer than the correspon-
> ding .o file and make will recompile all of them. That
> takes around 5 minutes and really slows development down.

> So I am looking for a way to tell sip to not re-create
> .cpp files when they aren't older than the correspon-
> ding .sip file or anything equivalent. Any ideas how
> to get this done?
I think that such a check wouldn't work in many cases.  However if sip would 
do a comparison of the existing .cpp file to the newly generated one, and only 
overwrite the existing one if there was a change, that should work properly in 
all cases.

I've been meaning to request this for a few years myself.

Matt





___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Just for fun: QCompleter accessing a QListWidget's internal model through a "proxy" ?

2010-08-17 Thread Matt Newell
On Tuesday 17 August 2010 11:23:55 fpp wrote:
> Hi everyone,
> 
> After many moons of lurking I have finally subscribed to ask for
> advice about my current challenge:
> 
> In this app I'm working on (my first "real", non-trivial one,
> admittedly), I have a number of QListWidgets in the main window,
> holding plain strings, each with an associated QLineEdit for input.
> They work just fine, and there really is no need for anything more
> elaborate than list widgets for what they do.
> 
> Only now that it's almost finished, with everything in place and the
> code working well, I just discovered the existence of QCompleters by
> accident... and obviously now I want them in the line edits.
> 
> However, QCompleters are designed to work only with "real" models, not
> convenience widgets. Of course it's very easy to use them with a plain
> QStringList, but it feels somewhat clunky and inefficient to duplicate
> the list widget's content to the completer's string list, refreshing
> it each time that content changes... and I don't really feel like
> retooling the entire UI to use QListViews just for the sake of
> completers.
> 
> So I thought, perhaps naively, that it might be possible to build a
> kind of "proxy" model, that would feed a completer with data pulled
> from a list widget's hidden, internal model.
> 
I could be overlooking something but I don't see why you can't use the list 
widget's model directly.  The details of the implemenation may be private, but 
the QAbstractItemModel interface is still public and usable.

Should be as simple as
completer = QCompleter( listWidget.model(), parent )

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] can't get findChild to work

2010-06-08 Thread Matt Newell
On Tuesday 08 June 2010 15:29:53 Danny Shevitz wrote:
> Howdy,
> 
> 
> 
> Another newbie question here. I am trying to get findChild to work. The
> code I am trying is
> 
> 
> 
> app=QtGui.QApplication.instance()
> 
> print app.allWidgets()
> 
> mdiArea=app.findChild(QtGui.QMdiArea)
> 
> print "in ElicitorPage, mdiArea = ",  mdiArea
> 
> 
> 
> As can be seen, I am getting the global application object, then printing
> all of its widgets (it is an MDI application with
> 
> a QMdiArea widget as the central widget). Then I try to find the QMdiArea
> widget. I don't believe I need a name in findChild
> 
> since the defaults to "" which matches all instances. I also tried with a
> name, and it didn't work for me anyway. In any case, here is the output
> 
> of the code:
> 
> 
> 
> [,  0x013F4078>,  .
> 
>  ]
> 
> in ElicitorPage, mdiArea =  None
> 
> 
> 
> As you can see, there is clearly a QMdiArea widget in app.allWidgets, and
> yet the findChild method doesn't return it.
> 
> Can anyone tell me what I am doing wrong?
> 

I think the problem is that the top level widgets aren't really children of 
the application from a QObject parent<->child standpoint.  The way to do this 
would be to loop through app.topLevelWidgets() calling findChild on each.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] splitters

2010-06-03 Thread Matt Newell
On Thursday 03 June 2010 11:06:04 Lic. José M. Rodriguez Bacallao wrote:
> no one?
> 
> On Wed, Jun 2, 2010 at 9:24 AM, Lic. José M. Rodriguez Bacallao
> 
>  wrote:
> > what I mean is something like the first case, and yes, I know that I
> > can nest several splitters but the problem is that I want that those
> > splitters in the first case have a common handler to resize all
> > splitted widgets at one time. Any suggestions?
> > 
> > PS: sorry for my English, it's not so good.
> > 


You should be able to embed two horizontal splitters inside a verticle 
splitter.  Keep the two horizontals in sync using a slot that reacts to 
either's  splitterMoved signal.  Then add a small center widget that allows 
resizing all 4 at once.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Re: [PyQt] Modifying tooltip before it is shown

2010-04-24 Thread Matt Newell
On Saturday 24 April 2010 03:53:46 detlev wrote:
> Hi,
>
> I would like to show the keyboard shortcut for a QAction in the tooltip.
> What would be the best way to amend the tooltip just before it is shown?
>
> Regards,
> Detlev

You can intercept QWidget's ToolTip event and change the tooltip text there.  
Unfortunately there is no event delivered to QActions, only QWidgets, so it 
may take some work depending on what widget is handling the QAction.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] openRPT and pyQT

2010-04-22 Thread Matt Newell

>
> Thanks for the response.  I guess I'm surprized that others don't know
> about openRPT.  I wonder what everyone is using for a report writer?  I'm
> using pyQT to write a CRUD app.  And I need a report writer.  I looked at
> reportlab but soon discovered openRPT.  The xTuple folks use it (both
> xTuple and openRPT writer were written in QT).
>
> So I guess the question is what is required to interface pyQT to other QT
> programs written in C++.  I realize that the question is very general.  But
> I hope others will provide at least a starting point for me.
I think it really depends on what you want to accomplish using python/pyqt.  
At the very least you'll have to write .sip bindings for whatever classes you 
want to use from python.  From there you'll need to make the app into a 
library so it's functionality can be used from a python script, and/or embed 
python into the program itself and add hooks in appropriate places.

For example if your goal is to use a template already created through the gui, 
and have a script load that template and generate reports automatically with 
different data sets, then you might need a fairly small subset of the 
programs functionality exposed to python.

If on the other hand you want to be able to embed python fragments into the 
forms, in order to manipulate the data in some way, that may require 
significant modification to the program itself.

No matter what you will have to become familiar with sip, and if you go the 
embedding route you will also have to become familiar with some of python's 
C-apis.

> What is 
> implied also in my question is the assumation that because openRPT (and
> others) were written in QT that should be some sort of standard way to
> interface from pyQT.
>
Writing sip bindings for C++ classes that use Qt is fairly straightforward in 
most cases.  IMO it can be learned quite quickly by looking at the .sip files 
used by PyQt4 itself, and referring to the docs when you don't understand 
what is what.

Matt


___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] openRPT and pyQT

2010-04-22 Thread Matt Newell
On Thursday 22 April 2010 14:10:33 John wrote:
> On Wednesday 21 April 2010 07:55:38 am John wrote:
> > I'm wondering if anyone has written an interface for openRPT.  As I
> > understand it "openRPT" is written in QT.So I'm guessing that openRPT
> > could be used by pyQT.
> >
> > Any help or discussion would be helpful.
> >
> > Johnf
>
> Did I ask a dumb newbie question?  I'm surprized no one even commented.
>

Probably because nobody on the list has heard of openRPT.  I hadn't.  Looks 
like an interesting project. 

I think if anyone had written bindings they would either announce it on the 
list here, or there would be info on the openRPT website.

It seems to me the main use of bindings for an app like that would be to embed 
python so you could use it to manipulate the sql data before it gets to the 
page.  That would probably require a decent amount of work on the 
application, besides writing the actual bindings.  Unlikely that someone 
would do that work unless they had specific requirements to fulfill.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QSqlDatabase connection parameters

2010-03-19 Thread Matt Newell
On Friday 19 March 2010 12:06:12 Scott Frankel wrote:
> Hi all,
>
> Would anyone have any suggestions for improving QSqlDatabase PSQL
> connection performance?
>
>
> The Qt docs refer to PSQL connection options and demonstrate the
> "requiressl=1" example.  Are there other options that can be set?
> (eg:  the docs' PostgreSQL "options" bullet point)  Google searches
> are coming up short.
>
> I note that my local postgresql.conf file has a "work_mem" statement.
> (Usage:  work_mem = 1MB)  That could be germane, but including the
> term in my setConnectOptions() method (as part of a semi-colon
> separated list) yields PSQL errors.
>
> I've optimized my working code further.  Running from a local data
> set, launch times are down to 4 seconds.  Running from an identical
> data set hosted remotely, my application launches in 40+ seconds!
>
> Thanks in advance!
> Scott
>
I always disable prepared connection inside the qsqlpsql driver, just add a 
return false; line after the PreparedQueries case statement in the 
hasFeatures function(that's all from memory, names may be off).  This will 
only help if you are using QSqlQuery.prepare, which i use for the api 
convenience, not because i actually want prepared queries.  This will reduce 
the roundtrip count and could make a difference if roundtrip time is an 
issue.

On the server you should enable logging of queries that take over a certain 
amount of time.  This will help you narrow down places where you need indexes 
or better designed queries.

Also it's possible to use multiple connection each from it's own thread.  I 
haven't done this in pyqt alone, but have done this quite a lot in c++/qt 
apps.

Other than that just reducing the total number of queries, which can be done 
by more intelligent/complex queries, or by stored procedures.

The qsqlpsql driver is a fairly thin wrapper around psql so I don't really 
think there is a lot of performance gains to be had by changing any settings.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] License for embedded PyQt in Qt C++ app

2009-12-18 Thread Matt Newell

> If you are not using PyQt you can release your application under LGPL.
>
> Sip license seems to allow that if I have properly understood it:
>
> http://www.riverbankcomputing.co.uk/software/sip/license
>
> If I have misunderstood it the rest of my mail will be senseless.
>
> At the moment you or your partners start programming using PyQt,
> you/they are bound to the GPL license. If you are distributing the
> source code and not charging anything, it should not make a difference
> to you. If your partners do not want to distribute their modified codes
> it does not make any difference to them either. So, you could clearly
> state it when distributing your code and say that if they use PyQt they
> are bound to the GPL license whenever they distribute derived work and
> that the only way to overcome that "problem" is to acquire a license
> from Riverbank.
>
> Armando
>

I'm pretty sure the c++ part of the application can be released under the LGPL 
or any license considered compatible with the GPL, so long as it doesn't 
depend on the pyqt modules built on top.  Any code derived from pyqt, 
directly or indirectly, would need to be licensed under the GPL, or developed 
with a commercial pyqt license.

To illustrate, if the application is split into 3 components:
A - The c++ part, which can be built and used without linking to sip or pyqt
B - The custom sip modules, which require both sip and pyqt
C - The application python scripts, which are derivative of A and B.

Both "B" and "C" must be released under the terms of the GPL unless you buy a 
commercial pyqt license.  "A" can be released under ANY license that is GPL 
compatible, such as the LGPL.

Here's a chart of license compatibility.
http://en.wikipedia.org/wiki/List_of_FSF_approved_software_licenses

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QObject.sender() bug

2009-11-24 Thread Matt Newell
On Monday 23 November 2009 13:53:09 Marcos Dione wrote:
> I think the backtrace is eloquent enough:
>
> --- traceback ---
> Traceback (most recent call last):
>   File
> "/home/mdione/src/projects/satyr/collection-agregator/satyr/models.py",
> line 97, in addSongs sender= QObject.sender ()
> TypeError: first argument of unbound method QObject.sender() must be a
> QObject instance
>
> --- traceback ---
> what's strange is that the sip file seems to be ok, but then I'm not
> familiar to sip files:
>
> --- code ---
> public:
> QObject *sender() const;
> %MethodCode
> // This is actually protected but we never need to call the real
> method. sipRes = qpycore_qobject_sender();
> %End
> --- code ---
>
> hints?

It's a member function so it needs the instance.  Usually that means calling
self.sender().

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] Problem with latest sip causing wrong function to be called(QVariant related)

2009-11-03 Thread Matt Newell

I have these two functions in a class. Same definition in both the .h and 
the .sip file.

MappedRecordList filter( const QString & column, const QVariant & 
value, bool 
keepMatches = true ) const;

MappedRecordList filter( const QString & column, const QRegExp & re, 
bool 
keepMatches = true ) const;


Called as

.filter('service',QRegExp('^Fusion'))

before it would call the second function as expected, now it is calling the 
first.  I'm not sure when this behavior started.  I am using sip 4.9.1.

I can write a test case if needed but i'm guessing you'll understand the issue 
without one.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Problem with latest sip causing wrong function to be called(QVariant related)

2009-11-03 Thread Matt Newell
On Tuesday 03 November 2009 09:53:32 Matt Newell wrote:
> I have these two functions in a class. Same definition in both the .h and
> the .sip file.
>
>   MappedRecordList filter( const QString & column, const QVariant & value,
> bool keepMatches = true ) const;
>
>   MappedRecordList filter( const QString & column, const QRegExp & re, 
> bool
> keepMatches = true ) const;
>
>
> Called as
>
> .filter('service',QRegExp('^Fusion'))
>
> before it would call the second function as expected, now it is calling the
> first.  I'm not sure when this behavior started.  I am using sip 4.9.1.
>
> I can write a test case if needed but i'm guessing you'll understand the
> issue without one.
>
> Matt
> ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt


I should have mentioned that i'm using pyqt 4.6.1. 

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Table changed/modified method

2009-10-21 Thread Matt Newell
On Wednesday 21 October 2009 14:49:28 Taylor Carrasco wrote:
> I'm looking for the exact same thing (to be notified when an item hierarchy
> changes) - but the following signal -
>
> self.connect(self.treeMain, SIGNAL('itemChanged(QTreeWidgetItem *, int)'),
> self.onItemChanged) # changes on init only
>
> is not emitted when an item is reparented. is there a way to do this?
>
> On Thu, Oct 22, 2009 at 8:01 AM, simozack  wrote:
> > 2009/10/21 Filippo Rebora :
> > > I'm using an extention of QtableWidget as table...is there anything
> > > like isModified() or something?
> > > Documentation didn't help (I could not find something similar in class
> > > or parents)
> >
> > You can use an attribute in the window class and set it to True if the
> > user modifies the data.
> >
> > In the function called when closing the window, you can test that
> > attribute.
> >
> > HTH,
> > Simone
> > ___
> > PyQt mailing listPyQt@riverbankcomputing.com
> > http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Use the QAbstractItemModel's signals for this.  rowsInserted/rowsRemoved 
signals should get called when an item is moved.

self.treeMain.model() # to get the QAbstractItemModel

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Table changed/modified method

2009-10-21 Thread Matt Newell
On Wednesday 21 October 2009 10:40:48 Filippo Rebora wrote:
> Hi,
> I have a small but incredibly time consuming problem
> I'm trying to find a way to create a conditional save method who, when you
> colse a window (with a table in it), finds out if it has been modified and
> if so asks you if you want to save data (quite standard, mh?=^D)
>
> I'm using an extention of QtableWidget as table...is there anything like
> isModified() or something?
> Documentation didn't help (I could not find something similar in class or
> parents)
>
> Thanks for help and sorry for bad English and ignorance in similar basic
> issue:blush:

Keep your own isModified variable, set it to true when the itemChanged signal 
is emitted. 

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Question regarding single model and multiple views...

2009-09-30 Thread Matt Newell
On Wednesday 30 September 2009 18:51:39 bvz wrote:
> Thanks for the quick reply.
>
> I was considering that (hiding columns) but that seems really really
> inefficient.  There could be as many as 25 tables with 7-8 columns each
> (but not much data... rarely more than 20 rows).  Hiding columns would mean
> a lot of duplicated info...
>
> 
>
> ...unless QT is smart enough not to populate the hidden columns?  That
> actually sounds like it could be the case here.  Hmmm.

It's not inefficient at all.  I'm pretty sure that none of the item views in 
qt would be asking for any data from the model for any hidden columns or 
rows.  

No info would be duplicated because the views don't store any data, they 
retrieve the data from the model on demand. 

>
> Your other suggestion to write a wrapper has me a little confused.  My data
> model already has the smarts to do all the filtering, it just doesn't know
> what table is requesting it. I don't understand how wrapping it in anything
> gets me any additional info.
>
The wrapper would simply make the existing model appear to only have the 
columns that each view desires.  So you would have an instance per view.  
Since it would only be passing on calls for data after mapping the 
QModelIndex, it wouldn't duplicate data or have much overhead. 

This isn't needed though if you simple need to hide columns, as QTreeView and 
QTableView both support that fine.

That's the very design of those classes, to show what columns you want, in 
what order you want.


Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Question regarding single model and multiple views...

2009-09-30 Thread Matt Newell
On Wednesday 30 September 2009 17:08:40 bvz wrote:
> Hello,
>
> I am new(ish) to PyQt and I am trying to build a simple app.
>
> The app has several tables that I want to point to a single model (which
> will load and store all the data).
>
> Each table is responsible for displaying a different set of columns from
> the model.  I.e. table 1 will show columns 1-4, table 2 columns 5-11,
> etc... The app does not know how many tables there will be ahead of time,
> nor does it know how many columns will be displayed in each table.  Both of
> these are set by reading a config file.
>
> I have a version working where I use a QTableWidget and manually sync the
> data from the "model" (not actually a subclass of QAbstractTableModel). 
> But there are some issues with this and, anyway, it isn't the "correct" way
> of working as far as I can tell.
>
> I really want to update the app to use the QAbstractTableModel (no
> delegates).  I mostly understand the process and am pretty far along with
> one exception.  How do I translate the "actual" column index in the table
> to the associated index in the model.  I.e. if the user updates a cell in
> column 3 of the 2nd table, that might actually be a bit of data that is in
> column 7 of the model.  I need to be able to map the table column to the
> model column and vice versa.
>
> So I am wondering, is there some way the table view can send along an
> offset every time it tries to send data to or from the model?  If I can get
> that info, I can always translate inside the model and return/set the
> correct data.
>
> Thanks.
The indexes should always match up.  Just use QTableView::setColumnHidden to 
hide the columns that aren't needed for each view.

If for some reason that didn't work it would be somewhat trivial to write a 
wrapper model that simply provides a subset of the real model.  Something 
like QSortFilterProxyModel, only a much simpler implementation as the mapping 
is always a constant operation.

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] casting issues

2009-09-16 Thread Matt Newell
On Wednesday 16 September 2009 16:28:52 Diez B. Roggisch wrote:
> Hi,
>
> when wrapping a C++-library with SIP ( 4.9-snapshot-20090821) I run into
> a couple of issues.
>
> First of all, the library I wrap has a hierarchy of classes (all
> descending from ISceneNode) which I wrapped.
>
> Now through an instance of a so-called ISceneManager, I can access
> instances of the current scene-graph which are ISceneNode-instances.
> Consequently, the signature for one of the accessory-methods looks like
> this:
>
>ISceneNode *getSceneNodeFromID(int)
>
> So far, so good.
>
> Now problem number one comes up: I *know* a certain node is of type e.g.
> IMeshSceneNode. But when I access it via the above method, all I get is
> an ISceneNode. My C++-foo is rusty, and I know that RTTI isn't always
> available - I just wonder: is there a way for SIP to figure out the
> actual type of the instance returned, and wrap it accordingly? If yes,
> what do I need to do to enable that feature?
>
> However, the library in question offers a getType()-call on ISceneNodes,
> and this I can use to write casting-code myself.
>

You need to implement %ConvertToSubClassCode, it's covered in the docs.

I have no idea about the crash.

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] 64 Bit windows installer for python 2.6

2009-08-17 Thread Matt Newell
Lacks a few features compared to phil's 32 bit installers, but i'll try to get 
them added as time permits. QScintilla and some sql drivers are what come to 
mind, there may be other things missing as well.  It does contain 
qsqlpsql(postgres) driver, phonon, webkit, and most/all the image formats.

By default installs to c:\python26_64\.

http://pyqt4-win64-binaries.googlecode.com/files/PyQt-Py2.6-gpl-4.6-snapshot-20090810-1.exe

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] GUI freezing when running large function in QThread

2009-07-22 Thread Matt Newell
On Wednesday 22 July 2009 14:12:11 Brent Villalobos wrote:
> Erik Janssens wrote:
> > If you interface to C code within your validation, does the interface
> > release the GIL ?
>
> Unfortunately I'm not much of a C person.  How do I check if the GIL has
> been released?


sip/PyQt is very aggressive when it comes to releasing the GIL.  Therefore if 
you are calling a lot of qt functions in your threads, it should be giving 
plenty of opportunities for other threads to run.  Especially if your threads 
are doing blocking operations where the GIL is released for longish periods 
of time.

If you are doing lots of python only processing in your threads that probably 
will cause the threads to hog the GIL and not allow others to run.  There are 
some options to allow other threads to run either at certain intervals or 
manually by calling time.sleep.  I'm not experienced with these techniques 
but a quick google search brings up some articles and discussions.
http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Which QStyle

2009-07-21 Thread Matt Newell
On Tuesday 21 July 2009 13:46:09 Mads Ipsen wrote:
> How do I programatically determine which style I am using, i.e. whether
> it's QWindowsStyle, QMacStyle, QMotifStyle etc.

style = QApplication.instance().style()
print style.metaObject().className()


Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] How to dynamically add widgets to a verticle layout?

2009-06-22 Thread Matt Newell
On Monday 22 June 2009 16:38:40 matt.dub...@sympatico.ca wrote:
> I too am hitting this roadblock.  Is there a way that the layout can
> automatically resize with the addition of new widgets?
>
> Matt Dubins
>
> -- Adam Chrystie wrote :
>
> As I add more QLineEdits, they are drawn closer and closer together and
> eventually overlap each other instead of drawing spaced apart from each
> other.
>
> Can anyone offer any tips to doing this?
>
> --
> This message was sent on behalf of matt.dub...@sympatico.ca at
> openSubscriber.com
> http://www.opensubscriber.com/message/pyqt@riverbankcomputing.com/9665274.h
>tml ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Trying calling resize on the widget using the result of layout.sizeHint().

I'm not sure that it'll work and I think it depends on how the layout is 
setup.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Compiling PyQt with windows

2009-06-04 Thread Matt Newell
On Thursday 04 June 2009 14:09:24 mel...@orangepalantir.org wrote:
> Okay I have MinGW32 and 64 bit python 2.6, I want to compile PyQt4 and I
> get a lot of errors similar too:
>
> undefined reference to '_imp__PyTuple_Pack'
>
> I hope the error is not because of the 64 bit version, it sounds like a
> library error.  Qt installed just fine though.
> I'm using the command
>
> c:\python26\python configure.py -p win32-g++
> mingw32-make
>
> thanks
> mbs

You can't use a 32 bit compiler(mingw32) to compile against 64 bit python.

You'll need to either use mingw-w64(which I haven't used successfully yet for 
Qt, and haven't tried with just pyqt), or one of the msvc compilers.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Re: PyQt Licensing

2009-05-06 Thread Matt Newell
On Wednesday 06 May 2009 20:58:12 Alberto Berti wrote:
> > "A Corsaire" == A Corsaire  writes:
>
> Phil>> First off, many thanks for not pestering me about this - it is
> Phil>> greatly appreciated.
> Phil>>
> Phil>> In a nutshell, the PyQt licensing will not be changed in the
> Phil>> short term.
>
> Corsaire>  that Python misses out on PyQt becoming
> Corsaire> the de-facto standard GUI library we sorely
> Corsaire> need.
>
> Differently from you, i'm  quite fine with PyQt licensing as it is now
> and i hope that Phil will have time and resources to continue its great
> work.
>
> What's i don't understand is the reason for not publishing a read only
> repository with the gpl code and even better also a bugtracker that
> allows developers and distribution packagers to track bugs and if and
> when their fix was applied to the sources.
>
> It seems to me that this would be a great help for the community and
> little effort for Phil and co. and the same time i don't see how it can
> damage Phil's business.
>
> The question raised already, but never receved a response.
>
> If this is just a problem about resources to setup and maintain it i can
> help with this. I even checked the possibility to apply all the history
> of the snapshots to a repo in the hope of tracking code changes, but
> older snapshots where unavailable last time i tried. Phil, please, could
> you share your thougts on this, frankly?
>
> azazel
>
> ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Even a read-only svn would be a big help for me and would save a lot of time 
and bandwidth for some users. Would be helpful for debugging and submitting 
patches. 

Matt



___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] compiling pyqt4 64-bit for local distribution

2009-05-06 Thread Matt Newell
On Wednesday 06 May 2009 14:49:26 Greg Smith wrote:
> Hi All,
> I was able to successfully compile Qt 4.5, SIP and PyQt4 on my dev
> machine using MSVC2005 (using 2005 because I am compiling against Python
> 2.5.1)
>
> I was successful in building everything and PyQt works on the dev
> machine. However I was curious on how I would be able to distribute PyQt
> to other machines at work? I'm fairly new with the world of compiling so
> I am not exactly sure what the process is to achieve what I am after.
>
> Thanks,
>
> Greg Smith
> Troublemaker Studios
>

PyQt.nsi is used to build an installer. Download and install the latest 
nullsoft installer package, right click on the PyQt.nsi and build it.  You 
can then run the installer with the silent option, /S, for automating the 
install via .bat scripts or whatever.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Crash in siplib.c:findSlot, with test case and fix

2009-04-23 Thread Matt Newell
On Thursday 23 April 2009 10:32:59 Matt Newell wrote:
> It seems if a wrapped class A has slots and a wrapped subclass B does not
> then an assert is triggered when calling a slot from A on an instance of B.
>
> To build and run the test --
>
> ./build.sh
> python test.py
>
>
> findSlot function that fixes all problems for me
>
> static void *findSlot(PyObject *self, sipPySlotType st)
> {
> sipPySlotDef *psd;
> PyTypeObject *py_type = Py_TYPE(self);
>
>   if( PySequence_Check( py_type->tp_bases ) ) {
>   int i = 0, end = PySequence_Size( py_type->tp_mro );
>   for( ; i < end; i++ ) {
>   PyObject * type_o = PySequence_GetItem( 
> py_type->tp_mro, i );
>   if( PyType_Check(type_o) ) {
>   PyTypeObject * py_type_to_check = 
> (PyTypeObject*)type_o;
>
>   /* If it is not a wrapper then it must be an 
> enum. */
>   if (PyObject_TypeCheck((PyObject 
> *)py_type_to_check,
> &sipWrapperType_Type))
>   psd = ((sipClassTypeDef 
> *)((sipWrapperType *)
> (py_type_to_check))->type)->ctd_pyslots;
>   else
>   {
>   assert(PyObject_TypeCheck((PyObject 
> *)py_type_to_check,
> &sipEnumType_Type));
>
>   psd = ((sipEnumTypeDef 
> *)((sipEnumTypeObject *)
> (py_type_to_check))->type)->etd_pyslots;
>   }
>   while (psd && psd->psd_func != NULL)
>   {
>   if (psd->psd_type == st)
>   return psd->psd_func;
>
>   ++psd;
>   }
>   } else
>   printf( "mro member not a type object\n" );
>   }
>   }
>
> assert(NULL);
>
> /* This should never happen. */
> return NULL;
> }



My "fix" fixes the test case but causes a crash with
QTreeWidgeItem() == None

so it's obviously not a solution.

Calling QTreeWidgetItem() == None without my change it ends up returning NULL 
from findSlot which the comment indicates should never happen.

Matt





___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] Crash in siplib.c:findSlot, with test case and fix

2009-04-23 Thread Matt Newell

It seems if a wrapped class A has slots and a wrapped subclass B does not then 
an assert is triggered when calling a slot from A on an instance of B.

To build and run the test --

./build.sh
python test.py


findSlot function that fixes all problems for me

static void *findSlot(PyObject *self, sipPySlotType st)
{
sipPySlotDef *psd;
PyTypeObject *py_type = Py_TYPE(self);

if( PySequence_Check( py_type->tp_bases ) ) {
int i = 0, end = PySequence_Size( py_type->tp_mro );
for( ; i < end; i++ ) {
PyObject * type_o = PySequence_GetItem( 
py_type->tp_mro, i );
if( PyType_Check(type_o) ) {
PyTypeObject * py_type_to_check = 
(PyTypeObject*)type_o;

/* If it is not a wrapper then it must be an 
enum. */
if (PyObject_TypeCheck((PyObject 
*)py_type_to_check, 
&sipWrapperType_Type))
psd = ((sipClassTypeDef 
*)((sipWrapperType *)
(py_type_to_check))->type)->ctd_pyslots;
else
{
assert(PyObject_TypeCheck((PyObject 
*)py_type_to_check, 
&sipEnumType_Type));

psd = ((sipEnumTypeDef 
*)((sipEnumTypeObject *)
(py_type_to_check))->type)->etd_pyslots;
}
while (psd && psd->psd_func != NULL)
{
if (psd->psd_type == st)
return psd->psd_func;

++psd;
}
} else
printf( "mro member not a type object\n" );
}
}

assert(NULL);

/* This should never happen. */
return NULL;
}


slot_crash_test.tar.gz
Description: application/tgz
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Re: [PyQt] Problem compiling SIP

2009-02-17 Thread Matt Newell
On Tuesday 17 February 2009 12:06:30 Francis Brissette wrote:
> Hello,
>
> I have installed MSVC2008 and Python26 on my Windows XP x64 machine but I
> have link errors while compiling SIP.
>
> Here what I have:
>
> C:\sip-4.7.9>python configure.py
> This is SIP 4.7.9 for Python 2.6.1 on win32.
> The SIP code generator will be installed in C:\Python26.
> The SIP module will be installed in C:\Python26\Lib\site-packages.
> The SIP header file will be installed in C:\Python26\include.
> The default directory to install .sip files in is C:\Python26\sip.
> The platform/compiler configuration is win32-msvc2008.
> Creating sipconfig.py...
> Creating top level Makefile...
> Creating sip code generator Makefile...
> Creating sip module Makefile...
>
> C:\sip-4.7.9>nmake
> ... (it's compiling) ...
>Creating library sip.lib and object sip.exp
> siplib.obj : error LNK2019: unresolved external symbol
> __imp___Py_NoneStruct referenced in function _setTraceMask qtlib.obj :
> error LNK2001: unresolved external symbol __imp___Py_NoneStruct threads.obj
> : error LNK2001: unresolved external symbol __imp___Py_NoneStruct
> siplib.obj : error LNK2019: unresolved external symbol
> __imp__PyArg_ParseTuple referenced in function _setTraceMask ... (other
> similar link errors) ...
>
> Do you have any idea how to fix these link errors ?
>
> Thanks,
> Francis

Are you sure the first python26.dll the linker is finding is 64 bit?


___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] PyQt for 64-bit Python on Windows

2009-02-17 Thread Matt Newell
On Tuesday 17 February 2009 00:23:45 V. Armando Sole wrote:
> Hello,
>
> At 12:26 16/02/2009 -0800, Matt Newell wrote:
> >Qt and PyQt work fine with 64 bit windows but I've been unable to get a
> >working Qt so far with mingw-w64.  I've had success with visual studio
> > 2005 and could provide installers.  I will need a few days though as I am
> > busy with other things atm.
>
> I just wanted to add a comment. Considering python 2.6 is supplied compiled
> with VS2008, perhaps you should consider using VS2008 express edition
> instead of VS2005. It is also free and better packaged than the 2005
> version.
>
> If you are talking about a binary for python 2.5 then, please, forget about
> my comment.
>
> Best regards,
>
> Armando

So far I have compiled against python 2.5 with vs2005.   I do plan to compile 
against 2.6, so I will use vs2008 for that.  Ultimately I would like to have 
all versions built with mingw-w64 but there was a gcc bug causing a crash 
when instantiating QCoreApplication with the version I tried.  This bug may 
have been fixed in the meantime so I will hopefully have it working in the 
near future.

Phil, would you be willing to host the installers?

Matt



___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] PyQt for 64-bit Python on Windows

2009-02-16 Thread Matt Newell
On Wednesday 11 February 2009 23:12:15 Dave Doty wrote:
> On Wed, Feb 11, 2009 at 2:04 AM, Phil Thompson
>
> wrote:
> > > The file c:\programs\Python26\include\Python.h does exist, with read
> > > permissions enabled, so I assumed that the inability to find it was
> >
> > either
> >
> > > an error in the build scripts, or my own misunderstanding of how to use
> > > them.
> >
> > Are you using Cygwin or just MinGW? I think Cygwin has given lots of
> > problems in the past.
>
> It's cygwin; that might explain the problems.
>
> > > In either case, a pre-compiled binary distribution of PyQt for
> > > Windows
> > > running 64-bit Python would allow me to skip all this. Is there such a
> > > package?
> >
> > Not to my knowledge.
> >
> > > Is it necessary to get one if I cannot build PyQt (or SIP) on my own?
> > > Or should it be possible to use this distribution:
> >
> > http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl
> >-4.4.4-2.exe
> >
> > > with 64-bit Python 2.6.1, through some other configuration trick?
> >
> > I doubt it.
> >
> > Phil
>
> Thank you for the information. It looks like wxPython is a better choice
> for my project, since it has a Windows installer that works out of the box
> with 64-bit Python.
>
> Dave

Qt and PyQt work fine with 64 bit windows but I've been unable to get a 
working Qt so far with mingw-w64.  I've had success with visual studio 2005 
and could provide installers.  I will need a few days though as I am busy 
with other things atm.

Unless it's a very small trivial project I would think the effort of compiling 
Qt and PyQt is well worth the effort compared to using wxPython.  I haven't 
looked a wxPython in a while though...

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Re: ConvertToSubClass problem

2008-11-19 Thread Matt Newell
On Wednesday 19 November 2008 03:05:50 Matteo Bertini wrote:
> Matt Newell ha scritto:
> > Could you be more specific about the situation that is failing.  What
> > actual type is the object, and what is the return type of the function
> > being called?
> >
> > Matt
>
> [EMAIL PROTECTED]:~/src$ cat bug_q3listview.py
>
> import sys
> from PyQt4.Qt import *
>
> if __name__ == "__main__":
> a = QApplication([])
> w = Q3ListView()
> w.addColumn("prova")
> i = Q3ListViewItem(w, "row1")
> print i, w.firstChild()
> print w, i.listView()
> w.show()
> #a.exec_()
>
> ### before the IsSubtype Fix
>
> [EMAIL PROTECTED]:~/src$ python bug_q3listview.py
> bug_q3listview.py:7: DeprecationWarning: Q3ListView constructor is
> deprecated
>   w = Q3ListView()
> bug_q3listview.py:9: DeprecationWarning: Q3ListViewItem constructor is
> deprecated
>   i = Q3ListViewItem(w, "row1")
> 
> 
> 
> 
>  ^^
> ## After the fix
>
> [EMAIL PROTECTED]:~/src$ python bug_q3listview.py
> bug_q3listview.py:7: DeprecationWarning: Q3ListView constructor is
> deprecated
>   w = Q3ListView()
> bug_q3listview.py:9: DeprecationWarning: Q3ListViewItem constructor is
> deprecated
>   i = Q3ListViewItem(w, "row1")
> 
> 
> 
> 
>   ^^
>


Thanks.

The actual bug is in q3frame.sip.

class Q3Frame : QWidget

should be

class Q3Frame : QFrame

as it is in qt's header files.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Re: ConvertToSubClass problem

2008-11-18 Thread Matt Newell

>
> If the above is fine, then the only problem must be in the code present
> in that patch. Does Matteo's suggestion of type equality ring you a
> bell? Otherwise I'll have a deeper debugging session. It would help if
> you could explain me the original purpose of that check (and
> generically, if you could describe the algorithm implemented by
> convertSubClass()).
>
The purpose of the check is to avoid having a class up-casted when proper 
convertToSubclass code is missing.

For example, if I write a new sip module:

class MyMainWindow : QMainWindow
{
... // No convertToSubclass defined
}

MyMainWindow * createMainWindow(); 

Without the check, the createMainWindow function will actually be returned as 
a QMainWindow object in python, because the convertToSubclass code for the 
QMainWindow class will return the sipClass_QMainWindow type.  The check makes 
sure if to return the original declared type unless a more specific type is 
found.

> > Did you build the above data structure by hand? Or have I given you a
> > copy of my script that automatically generates it?
>
> By hand :) But I think the data structure per-se is correct. I have
> reviewed it many times, and I have even verified that, when that
> convertor is called, the correct result is returned but it is then
> discarded because of that specific subtype check (whose purpose is still
> unknown to me).
Could you be more specific about the situation that is failing.  What actual 
type is the object, and what is the return type of the function being called?

Matt


___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Re: How do I intercept widget destruction?

2008-10-22 Thread Matt Newell
On Wednesday 22 October 2008 09:49:58 Jeremy Sanders wrote:
> Matt Newell wrote:
> > If you subclass you can override QWidget.closeEvent, QWidget.hideEvent,
> > or the destructor.
>
> Thanks - I tried to override closeEvent but it never seems to get called.
> Is there some trick? This is for a QLineEdit.
>
> Jeremy

close events are only delivered to top level windows.  You either need to use 
hideEvent on the line edit, or closeEvent on it's window().

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] How do I intercept widget destruction?

2008-10-22 Thread Matt Newell
On Wednesday 22 October 2008 09:31:18 Jeremy Sanders wrote:
> Hi - this may be an FAQ, but I haven't seen it.
>
> Is it possible to receive notification just before a QWidget is destroyed
> in Python by subclassing? I'd like to call some cleanup routines for a
> custom widget when it is removed from the screen.
>
> Thanks
>
> Jeremy

If you subclass you can override QWidget.closeEvent, QWidget.hideEvent, or the 
destructor.

If you want to moniter it without subclassing, you can use an event filter or 
connect to the QObject.destroyed signal.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] Handling python exceptions in virtual overrides

2008-09-03 Thread Matt Newell

If I understand correctly, there is currently no way to "handle" python 
exceptions that occur inside a python member function when called via a c++ 
virtual function.

%MethodCode is insufficient because it is never called when the member 
function is called via a c++ virtual function.

%VirtualCatcherCode is insufficient because you have no access to sipCpp, 
sipSelf, etc.


I think a workable solution would be a new directive %VirtualErrorCode.

A generated virtual function with %VirtualErrorCode could look like the 
following

void sipMyClass::myVirtualMember()
{
extern void sipVH_MyModule_1(sip_gilstate_t,PyObject *);

sip_gilstate_t sipGILState;
PyObject *meth;

meth = 
sipIsPyMethod(&sipGILState,&sipPyMethods[16],sipPySelf,NULL,sipNm_MyModule_myVirtualMember);

if (!meth)
{
MyClass::myVirtualMember();
return;
}
bool isError = false;
sipVH_MyModule_1(sipGILState,meth,&isError);
if( isError ) {
// %VirtualErrorCode inserted here
}
}

The virtual handler functions would only need a param bool * isError. If 
isError is 0, then they would call PyErr_Print() as they do currently, else 
they will set *isError = true and return without clearing the exception.

The %VirtualErrorCode would be responsible for clearing the exception.

I can probably come up with a working patch next week if you think this is a 
workable solution.

This could probably later be expanded to do python -> c++ exception mapping.

Thanks
Matt


___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] SIP - %Exception for StopIteration

2008-08-05 Thread Matt Newell
On Tuesday 05 August 2008 16:43:36 Jonny Morrill wrote:
> Hello,
>
> I have just started using sip to create python extensions for a few of my
> C++ libraries. I have had success with most everything I wanted to do.
> There is one thing I could use some help with, though. I wanted to use one
> of my C++ classes as if it were an iterable python object. To get this to
> work, I implemented the required functions in my C++ code:
>
> (using Object as an example class name)
>
> Item* Object::next();
> Item* Object::operator[](int index);
> Object* Object::__iter__();
>
> When I create a python object I now can do something like:
>
> object = Object()
> .
> .
> .
> for *item* in *object*:
>   // item is an Item object
>
> This causes an infinite loop and I am pretty sure that it is because the
> Item* Object::next(); function is missing the raise StopIteration exception
> that is present in all python iterable objects. I think that using the
> %Exception directive in my specification file should lead me to a solution,
> but the syntax is somewhat confusing to me. I actually do not have mush
> experience with exceptions in C++ so a basic explanation of what needs to
> be coded in both the C++ and .sip file would be very much appreciated!!
>
> Also, if there is a better way to do this I would be happy to hear it!
>

I can't answer your question about StopIteration exception, but I have 
iteration working fine with my bindings by simply implementing __len__ and 
operater[].   I have no __iter__ or next functions.  There's probably more 
efficient ways to do it(especially depending on your operator[] 
implementation), but it works.

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Faster transparency from a QImage?

2008-06-17 Thread Matt Newell
On Tuesday 17 June 2008 13:17:00 Jeiel Aranal wrote:
> Is there a faster way to draw transparency on a QWidget from a QImage
> other than converting the QImage to a pixmap and setting that as the
> mask? I'm trying to have a 3d window draw into PyQt, the window output
> is going in fast enough but getting the alpha of the 3d window into
> the mask is being way too slow for my purpose. My paint event:
>
> def paintEvent(self,  event):
> if self.pandaTexture.mightHaveRamImage():
> self.pandaTexture.setFormat(Texture.FRgba32)
> #print "Should draw yes?"
> data = self.pandaTexture.getRamImage().getData()
> img = QtGui.QImage(data, self.pandaTexture.getXSize(),
> self.pandaTexture.getYSize(), QtGui.QImage.Format_ARGB32).mirrored()
> self.paintSurface.begin(self)
> self.paintSurface.drawPixmap(0, 0, self.desktopBg)
> self.paintSurface.drawImage(0, 0, img)
> self.paintSurface.end()
> pixmap = QtGui.QPixmap.fromImage(img)
> self.setMask(pixmap.mask())


I think QWidget.setMask will always be slow.  I think the only way to 
accomplish a changing mask is to use a visual that supports a true alpha 
channel, instead of using setMask.

You will also need to avoid so many copies of the data depending on how fast 
you need it.  The code above has at least 3 copies, possibly 5, plus the 
pixmap.mask and QWidget.setMask calls.  This is probably fine if the image is 
small, but will be prohibitively slow if the image is large.

The details of doing this will vary somewhat depending on what platform you 
are using.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Re: Template -> unsupported function return type

2008-06-13 Thread Matt Newell
On Friday 13 June 2008 08:04:46 Arve Knudsen wrote:
> Looks like I made it work, somehow. Anyway, I refer to the class
> template in the SIP specification using a typedef. That leads to
> another problem, however. The generated code refers to the typedef,
> but lacks its definition. How do I include the header containing the
> typedef?? For a class I would use %TypeHeaderCode, but can't see
> anyway of doing the same for typedefs ..
>

%ModuleHeaderCode
#include "myheader.h"
%End

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Various problems with QGraphicsView

2008-06-06 Thread Matt Newell
On Tuesday 03 June 2008 09:50:50 Luke Campagnola wrote:
> Hello again,
> I am trying to implement a subclass of QGraphicsView that allows the
> user to pan its contents by dragging with the middle mouse button and
> scale by dragging with the right button. for various reasons, I do not
> wish to use the built-in pan and zoom features in QGraphicsView. I
> have read several posts online from people trying to accomplish
> similar tasks but haven't really seen any satisfactory answers, and
> I've been banging my head against this problem for a long while now.
>
> Here is my basic approach: subclass QGraphicsView, reimplement all
> mouse event functions so that I can catch the ones I recognize,
> translate/scale the graphicsview, and pass on the remaining events.
>
> Here are the problems I have run into:
>
>  - If I catch ALL mouse events and never pass any on to the
> QGraphicsView handlers, everything works fine. If, however, I do pass
> some (but not all) events to the superclass, then I start to get some
> very erratic behavior--maybe 1 out of every 100 mouse events has the
> incorrect position, sometimes more. I've attached a program that
> demonstrates this--you can drag with the right mouse button with no
> trouble until the left mouse button (which is passed on to the
> superclass) is clicked. After clicking the left mouse button, dragging
> with the right mouse button should work most of the time but
> occasionally the scene will jump erratically.
>
>  - If, on the other hand, I pass ALL events to the superclass, then
> every once in a while the mouseMoveEvent will start getting called
> repeatedly in the absence of any events, usually tying up the CPU in
> the process.
>
>  - self.translate() does not work (seemingly under any
> circumstances?). This has been discussed a few times before, and seems
> to be caused by the graphicsView wanting to automatically center the
> scene contents after translating them. My workaround looks like this
> (working example attached):
>  - in GraphicsView.__init__(), I have:
> self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor)
> self.setSceneRect(QtCore.QRectF(-1e100, -1e100, 1e100, 1e100))
>  - Instead of using self.translate(x, y), I use:
>  m = self.matrix()
>  m.translate(x, y)
>  self.setMatrix(m)
>  I don't know exactly all of these together produce a workable
> solution, but it seems like a lot of work to accomplish such a simple
> task.
>
>  - It is difficult to get full control of the viewport, presumably
> because QAbstractScrollArea (or possibly QGraphicsView?) likes to move
> the scene around without telling me (particularly when resizing the
> window). My workaround to this has been to reset any unexpected
> transformations like this:
>self.resetMatrix()
>center = self.mapToScene(self.width()/2., self.height()/2.)
>m = QtGui.QMatrix()
>m.translate(center.x(), center.y())
>self.setMatrix(m)
>  I have left this out of the attached example, and as a result I know
> no reliable way of knowing where exactly my graphics are drawn within
> the widget.
>
>  - It appears that the event object that gets passed to the
> mouseEvent functions is being reused. This caused an unexpected (but
> easily fixed) problem for me: In order to allow scene panning/scaling,
> I need to record the event.pos() for every mouse event so that I can
> compare the previous event position to the current event position.
> Since the event object is reused, however, I find that the position I
> stored as the "previous position" has already been updated to the
> current position. For example:
>  ## Does not work
>  self.lastMousePosition = event.pos()
>  ## Workaround
>  self.lastMousePosition = QPoint(event.pos().x(), event.pos().y())
>
>
> In summary, my questions:
> 0. Why might I be having so much difficulty handling mouse events?
> 1. Is there a better / recommended way to accomplish the type of user
> interaction I'm after?
> 2. Is there some unambiguous way to set the transformation matrix used
> by QGraphicsView that will not be interfered with?
> 3. Is there a simple way to make translate() work?
>
> I'd love to hear any workable solutions other people have found.. I've
> been tempted to just go back to using QPainter, but the features in
> QGraphicsView are just too good to pass up :)
> Thanks!
> Luke

1.   Translate works the exact same as what you are doing with
>  m = self.matrix()
>  m.translate(x, y)
>  self.setMatrix(m)
the actual code is
void QGraphicsView::translate(qreal dx, qreal dy)
{
Q_D(QGraphicsView);
QTransform matrix = d->matrix;
matrix.translate(dx, dy);
setTransform(matrix);
}

and setMatrix simply calls setTransform.
  Setting NoAnchor should keep it from moving it behind your back whether 
you call setTransform, setMatrix, or translate.

2. For some reason QGraphicsView "replays" mouse events.  One of the places 
this is done is inside ::setTra

Re: [PyQt] Various problems with QGraphicsView

2008-06-03 Thread Matt Newell
On Tuesday 03 June 2008 10:11:51 Phil Thompson wrote:
> On Tuesday 03 June 2008 5:50:50 pm Luke Campagnola wrote:
> >  - It appears that the event object that gets passed to the
> > mouseEvent functions is being reused. This caused an unexpected (but
> > easily fixed) problem for me: In order to allow scene panning/scaling,
> > I need to record the event.pos() for every mouse event so that I can
> > compare the previous event position to the current event position.
> > Since the event object is reused, however, I find that the position I
> > stored as the "previous position" has already been updated to the
> > current position. For example:
> >  ## Does not work
> >  self.lastMousePosition = event.pos()
> >  ## Workaround
> >  self.lastMousePosition = QPoint(event.pos().x(), event.pos().y())
>
> You just need to do...
>
> self.lastMousePosition = QPoint(event.pos())
>
> This is a fairly common problem caused by '=' in Python meaning something
> different to '=' in C++. In the latter you would implicitly invoke the copy
> ctor, but Python requires you to be explicit.
>
> It's on the TODO list to automatically make a copy of a const reference.
>
> Phil


In this case that isn't the problem.  I was getting incorrect results from 
QMouseEvent::buttons() inside qt code after setting breakpoints with gdb, 
before the event ever reached pyqt code.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Various problems with QGraphicsView

2008-06-03 Thread Matt Newell
On Tuesday 03 June 2008 09:50:50 Luke Campagnola wrote:
> Hello again,
> I am trying to implement a subclass of QGraphicsView that allows the
> user to pan its contents by dragging with the middle mouse button and
> scale by dragging with the right button. for various reasons, I do not
> wish to use the built-in pan and zoom features in QGraphicsView. I
> have read several posts online from people trying to accomplish
> similar tasks but haven't really seen any satisfactory answers, and
> I've been banging my head against this problem for a long while now.
>
> Here is my basic approach: subclass QGraphicsView, reimplement all
> mouse event functions so that I can catch the ones I recognize,
> translate/scale the graphicsview, and pass on the remaining events.
>
> Here are the problems I have run into:
>
>  - If I catch ALL mouse events and never pass any on to the
> QGraphicsView handlers, everything works fine. If, however, I do pass
> some (but not all) events to the superclass, then I start to get some
> very erratic behavior--maybe 1 out of every 100 mouse events has the
> incorrect position, sometimes more. I've attached a program that
> demonstrates this--you can drag with the right mouse button with no
> trouble until the left mouse button (which is passed on to the
> superclass) is clicked. After clicking the left mouse button, dragging
> with the right mouse button should work most of the time but
> occasionally the scene will jump erratically.
>
>  - If, on the other hand, I pass ALL events to the superclass, then
> every once in a while the mouseMoveEvent will start getting called
> repeatedly in the absence of any events, usually tying up the CPU in
> the process.
>
>  - self.translate() does not work (seemingly under any
> circumstances?). This has been discussed a few times before, and seems
> to be caused by the graphicsView wanting to automatically center the
> scene contents after translating them. My workaround looks like this
> (working example attached):
>  - in GraphicsView.__init__(), I have:
> self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor)
> self.setSceneRect(QtCore.QRectF(-1e100, -1e100, 1e100, 1e100))
>  - Instead of using self.translate(x, y), I use:
>  m = self.matrix()
>  m.translate(x, y)
>  self.setMatrix(m)
>  I don't know exactly all of these together produce a workable
> solution, but it seems like a lot of work to accomplish such a simple
> task.
>
>  - It is difficult to get full control of the viewport, presumably
> because QAbstractScrollArea (or possibly QGraphicsView?) likes to move
> the scene around without telling me (particularly when resizing the
> window). My workaround to this has been to reset any unexpected
> transformations like this:
>self.resetMatrix()
>center = self.mapToScene(self.width()/2., self.height()/2.)
>m = QtGui.QMatrix()
>m.translate(center.x(), center.y())
>self.setMatrix(m)
>  I have left this out of the attached example, and as a result I know
> no reliable way of knowing where exactly my graphics are drawn within
> the widget.
>
>  - It appears that the event object that gets passed to the
> mouseEvent functions is being reused. This caused an unexpected (but
> easily fixed) problem for me: In order to allow scene panning/scaling,
> I need to record the event.pos() for every mouse event so that I can
> compare the previous event position to the current event position.
> Since the event object is reused, however, I find that the position I
> stored as the "previous position" has already been updated to the
> current position. For example:
>  ## Does not work
>  self.lastMousePosition = event.pos()
>  ## Workaround
>  self.lastMousePosition = QPoint(event.pos().x(), event.pos().y())
>
>
> In summary, my questions:
> 0. Why might I be having so much difficulty handling mouse events?
> 1. Is there a better / recommended way to accomplish the type of user
> interaction I'm after?
> 2. Is there some unambiguous way to set the transformation matrix used
> by QGraphicsView that will not be interfered with?
> 3. Is there a simple way to make translate() work?
>
> I'd love to hear any workable solutions other people have found.. I've
> been tempted to just go back to using QPainter, but the features in
> QGraphicsView are just too good to pass up :)
> Thanks!
> Luke

I was investigating the bug wrt mouse events, specifically that buttons() 
returns incorrect values after the first click-release sequence.  I haven't 
pinpointed the problem yet, but I think this may be a Qt bug and not a PyQt 
bug.  

The QMouseEvent object is not actually reused, but is created on the stack at 
such a low level in the call stack that it occupies the same address.

When I get a chance I will look into this further.

BTW, have you checked the trolltech bug tracker to see if this issue has been 
reported?

Matt


___
PyQt mailing listPyQt@riverb

Re: [PyQt] QThread problem using PyQt4.4.2

2008-05-23 Thread Matt Newell
On Friday 23 May 2008 09:06:12 Stanislas Marquis wrote:
> Hello all,
> I'm facing a problem with threads. The strange part of it is that it
> was working fine with PyQt4.3.x.
> It seems like inside the thread it's not able to "import" modules or
> access variables anymore. All I get is tracebacks like:
>
...
> I know threading is a difficult matter and I'm no expert at all, but
> the code used to run Ok under PyQt4.3, so I'm asking, did anything
> change, what should I be aware of?
>
> Thanks in advance,
> SM.

Does it consistently error on the first import or variable use, or is it 
somewhat random?

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] beginner, array setdata, write back

2008-05-22 Thread Matt Newell
On Thursday 22 May 2008 08:32:27 ulrichD wrote:
> I'm a novice to pyqt and search for something so basic, it's embarrassing.
> Unfortunately I still couldn't find any answer in the net (probably don't
> even know what to search for)
> (in addition i hope I know dontt post twice now, the first time I got an
> mail saying it was rejected)
>
> I simply want a gui to show me the content of an numpy array. When I change
> a value in the gui, i want this to be written back into the array.
>
> I tried something like:
>
>
> XX
> from __future__ import division
> import sys
> from math import *
> from PyQt4.QtCore import *
> from PyQt4 import QtCore
> from PyQt4.QtGui import *
>
> class sheet(QDialog):   #By inheriting QDialog we get a blank form, that
> is, a gray rectangle, and some convenient behaviors and methods
> def __init__(self, arr, parent=None):#A widget that has no parent
> becomes a top-level window
> QWidget.__init__(self)
>
> tablemodel = MyTableModel(arr, self)
> self.tabmod=tablemodel
>   tableview = QTableView()
> tableview.setModel(tablemodel)
>
> layout = QVBoxLayout(self)
> layout.addWidget(tableview)
> self.setLayout(layout)
>
> class MyTableModel(QAbstractTableModel):
> def __init__(self, datain, parent=None):
> QAbstractTableModel.__init__(self, parent)
> self.arraydata = datain
>
> def rowCount(self, parent):
> return len(self.arraydata)
>
> def columnCount(self, parent):
> return len(self.arraydata[0])
>
> def data(self, index, role):
> if not index.isValid():
> return QVariant()
> elif role != Qt.DisplayRole:
> return QVariant()
> return QVariant(self.arraydata[index.row()][index.column()])
>
> def isEditable(self, index):
> """ Return true if the index is editable. """
> return True
>
> def flags(self, index):   #function is called to chaeck if itmes are
> changable etc, index is a PyQt4.QtCore.QModelIndex object
> if not index.isValid():
> return QtCore.Qt.ItemIsEnabled
>
> ret_flags = QtCore.Qt.ItemIsSelectable |
> QtCore.QAbstractItemModel.flags(self, index)
> if self.isEditable(index):
> #print index.row()  #returns the selected elements row
>   #print index.column()
>   ret_flags = ret_flags | QtCore.Qt.ItemIsEditable
> return ret_flags
>
>
> def setData(self, index, value, role):
>   """ if a item is edited, this command is called
>   value.toString() constains the new value
>   cahnge here to have it evaluate stuff!"""
>   self.arraydata[index.row(),index.column()]=value.toString()
> #<<< the problem (i think)
>
>
> X
>
> if this file is called ugui.py, it hem run it from the shell with
>
> import ugui
> arr=rand(3,3)
> form = ugui.sheet(arr)
> form.show()
>
> I think I encounter two problems:  I access the newly entered data
> incorrectely and there seems to be a variable type issue.
>
> Maybe someone can help me out here?

You need to return the data with both Qt.DisplayRole AND Qt.EditRole.  You 
need to return True in setData, and you need to use value.toFloat() or 
toInt() or whatever type you want that the numpy array will accept.

btw, next time it would be nice if the example would be runnable just by 
pasting into a text file, it took me a while to figure out where the 
rand(3,3) function came from...

Also, you might have to mess with the delegate to get the desired editting 
precision.

Matt



numpy_model_working.py
Description: application/python
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Re: [PyQt] QT_SHARED not defined

2008-05-13 Thread Matt Newell
On Tuesday 13 May 2008 00:56:08 Phil Thompson wrote:
> On Tuesday 13 May 2008 00:10:50 Matt Newell wrote:
> > On Friday 09 May 2008 15:28:09 Phil Thompson wrote:
> > > On Friday 09 May 2008 22:13:39 Matt Newell wrote:
> > > > Using  vanilla qt-x11-4.4.0 with PyQt-x11-gpl-4.4-snapshot-20080508
> > > > and sip-4.7.5-snapshot-20080507.
> > > >
> > > > Not a problem for me to work around, just thought you might want to
> > > > know this is still an issue, and afaict is not related to any
> > > > distribution issues.
> > >
> > > What are the circumstances in which it needs to be defined?
> >
> > PyQt's configure script errors with "Qt has been built as static
> > libraries so either the -g or -k argument should be used." even though qt
> > is built as regular shared libs.
>
> Obviously I've never seen the problem.
>
> > I believe I had the same problem with earlier version of pyqt and just
> > hacked the configure.py script to work around it, which I believe is the
> > same thing the distro's are doing.  Probably an inconsistency with the
> > qmakespecs or something, I haven't looked into it further.
>
> The error message will appear if the test program finds that neither
> QT_SHARED or QT_DLL are defined.
>
> The .pro file that configure.py generates includes "CONFIG += link_prl" as
> a workaround for broken Linux distros not setting QT_SHARED properly. This
> is ignored by a normal Qt build.
>
> Can you suggest a different workaround for your distro?

Phil, this looks like a Qt bug to me.  Qt's configure script has code to 
detect gnu make(if CFG_GNU_MAKE="auto"), but sets CFG_GNU_MAKE=no initially, 
so the check is never done.

Then, when generating the makefiles(qmake/generators/unix), it only includes 
PRL_EXPORT_DEFINES, which has QT_SHARED, if include_deps is true, and 
include_deps is only true if using gnumake.

So the workaround is to pass --enable-gnumake to Qt's configure script.  

I think the bug is that PRL_EXPORT_DEFINES should be included no matter what 
the value of include_deps is(as they are included in all cases with each of 
the other qmake generators), and qt should also be running the auto detection 
code for gnumake.  I will file a bug report.

Matt




___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QT_SHARED not defined

2008-05-12 Thread Matt Newell
On Friday 09 May 2008 15:28:09 Phil Thompson wrote:
> On Friday 09 May 2008 22:13:39 Matt Newell wrote:
> > Using  vanilla qt-x11-4.4.0 with PyQt-x11-gpl-4.4-snapshot-20080508 and
> > sip-4.7.5-snapshot-20080507.
> >
> > Not a problem for me to work around, just thought you might want to know
> > this is still an issue, and afaict is not related to any distribution
> > issues.
>
> What are the circumstances in which it needs to be defined?
>

PyQt's configure script errors with "Qt has been built as static libraries so 
either the -g or -k argument should be used." even though qt is built as 
regular shared libs.

I believe I had the same problem with earlier version of pyqt and just hacked 
the configure.py script to work around it, which I believe is the same thing 
the distro's are doing.  Probably an inconsistency with the qmakespecs or 
something, I haven't looked into it further.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] question re: QVariant formatting in QTableWidgetItem

2008-05-10 Thread Matt Newell
On Saturday 10 May 2008 11:49:38 Brian Gyss wrote:
> All:
>
> I'm having some issues changing the formatting of a number in a
> QTableWidgetItem.  It seems that whenever I feed any sort of number
> with non-zero digits in front of a decimal point into the QVariant
> type, the QTableWidgetItem will always display the formatting to 6
> digits in a specific format.
>
> For example, a number like this:
>
> 10454.450432
>
> will always be depicted like this:
>
> 10,454.4
>
> when the specific item is inserted in a table.  Also, I need to use
> QTableWIdgetItem.setData() in order to insert the numeric data or else
> the numbers in the table are not sortable.
>
> Do I have to subclass either QVariant or QTableWidgetItem in order to
> change the formatting of how numbers are depicted inside of
> QTableWidget cells, or is there a more succinct way of doing this?
>
> Thanks!
>
> - Brian

I think you have 2 options.

1) Subclass QTableWidgetItem.  override the data function, return a formatted 
string for DisplayRole, and float/double for EditRole.  You'll also have to 
override the operator< to get proper sorting, because I believe the default 
implemenation uses the DisplayRole for sorting.

2) Subclass QItemDelegate and have it do the formatting. 

#1 is probably easier.

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] QT_SHARED not defined

2008-05-09 Thread Matt Newell
Using  vanilla qt-x11-4.4.0 with PyQt-x11-gpl-4.4-snapshot-20080508 and 
sip-4.7.5-snapshot-20080507.

Not a problem for me to work around, just thought you might want to know this 
is still an issue, and afaict is not related to any distribution issues.

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Pixel pushing performance

2008-05-07 Thread Matt Newell
On Wednesday 07 May 2008 18:59:33 Roberto Alsina wrote:
> >
> >  def paintEvent(self, event):
> >  canvas = QtGui.QImage(event.rect().size(),
> >QtGui.QImage.Format_RGB32)
> >  for i in xrange(0, canvas.height()):
> >  for j in xrange(0, canvas.width()):
> >  canvas.setPixel(j, i, 123456)
> >  painter = QtGui.QPainter()
> >  painter.begin(self)
> >  painter.fillRect(event.rect(), QtGui.QBrush(canvas))
> >  painter.end()
> >
> > Obviously, in my real application the inner statement in the loop is a
> > bit more complex, but even the above example is slow when the widget is
> > fairly large (e.g. 300x300px). Is there a way to speed this up?
>
> Try putting very little busywork in there instead of a setPixel (like,
> calculate a square root),and I bet that will slow enough to be noticeable,
> too.
>
> You need to find a way not to *have* to do that, or you will need to do it
> outside python. 300x300 are 90K iterations. 90K anything takes a little
> while.
>
>    

Yep, and even if you wrote the loop in C++ it would still be slow because 
setPixel is a non-inlined function.  It would probably be 10x-100x faster by 
doing pointer arithmetic and avoiding the function call, though none of that 
matters as long as the loop is in python.

Basically you have two choices
1) Avoid per-pixel drawing for real time updates, either by caching or drawing 
with primitives through the qpainter or opengl apis(, or numpy, but I don't 
know about that).
2) Use optimized lower level drawing code written in C/C++

Matt

___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Re: SIP - patched methods with lazy lookups

2008-04-22 Thread Matt Newell
On Tuesday 22 April 2008 10:47:12 Kevin Watters wrote:
> > old_init = MyClass.__init__ def new_init(self, foo, bar=5, meep=13):
> > old_init(self, foo, bar, meep) MyClass.__init__ = new_init
> >
> > assert MyClass.__init__ is new_init # FAIL
>
> Oops. That should be
>
> old_init = MyClass.__init__
> def new_init(self, foo, bar=5, meep=13):
> old_init(self, foo, bar, meep)
>
> MyClass.__init__ = new_init
>
> assert MyClass.__init__ is new_init # FAIL
>
>
> ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt


We are doing something similar.  It works if you create a new class that 
inherits from MyClass, then replace MyClass with the new one.

class MyClassOverride(MyClass):
def __init__(self, food, bar=5, meep=13):
MyClass.__init__(self,foo,bar,meep)

MyClass = MyClassOverride

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Construct QVariant from object of user type

2008-04-18 Thread Matt Newell


Here is working code(though not in compilable form) that allows registering 
python classes(really any python object that has .__name__ attribute) as a 
QMetaType. Then you use qvariantFromPyObject to construct a qvariant from an 
instance of the registered type.  You use pyObjectFromQVariant to get the 
python object back.

This code could be modified to provide a single QMetaType for any PyObject.  
This would allow storing any python object without having a specific type 
registered.  Specific type registration is useful for thing like 
QItemEditorFactory, so the ability to register custom types should remain.

This code could quite easily be integrated into the QVariant .sip bindings to 
provide a QVariant ctor that takes any PyObject, and a QVariant function that 
returns the PyObject.

Phil, are you interested in having this functionality directly in PyQt?  I 
would be willing to integrate but don't really have time to do so at the 
moment. (It would only take a few minutes to integrate, but I would have to 
update my sip and pyqt to the latest versions first)

btw. The code i pasted is written to be compiled outside of a sip module, 
therefore uses a bit of hackery to get at the sip api.  This would not be 
needed if it was integrated into PyQt.


>>> class A:
... pass
...
>>> metaTypeId = registerPythonQMetaType(A)
>>> print metaTypeId
424
>>> qv = qvariantFromPyObject(A())
>>> qv

>>> qv.userType()
424
>>> print qv.typeName()
A
>>> pyObjectFromQVariant(qv)
<__main__.A instance at 0xb65391ec>

Matt

.sip

int registerPythonQMetaType( SIP_PYOBJECT type ) /HoldGIL/;
SIP_PYOBJECT qvariantFromPyObject( SIP_PYOBJECT object ) /HoldGIL/;
SIP_PYOBJECT pyObjectFromQVariant( SIP_PYOBJECT py_qvariant ) /HoldGIL/;

.h

extern "C" {
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
};

int registerPythonQMetaType( PyObject * type );
PyObject * qvariantFromPyObject( PyObject * object );
PyObject * pyObjectFromQVariant( PyObject * py_qvariant );

.cpp

#include 

static inline void ensurePythonInitialized()
{
	if( ! Py_IsInitialized() )
		Py_Initialize();
}

const sipAPIDef * getSipAPI()
{
	ensurePythonInitialized();

	static const sipAPIDef * api = 0;
	if( api ) return api;

	/* Import the SIP module and get it's API.
	 * libsip does not provide a symbol for accessing the sipAPIDef object
	 * it must be retrieved through sip's python module's dictionary
	 */
SIP_BLOCK_THREADS
	PyObject * sip_sipmod = PyImport_ImportModule((char *)"sip");
	if (sip_sipmod == NULL) {
		LOG_3( "getSipAPI: Error importing sip module" );
	} else {

		PyObject * sip_capiobj = PyDict_GetItemString(PyModule_GetDict(sip_sipmod),"_C_API");
	
		if (sip_capiobj == NULL || !PyCObject_Check(sip_capiobj))
			LOG_3( "getSipAPI: Unable to find _C_API object from sip modules dictionary" );
		else
			api = reinterpret_cast(PyCObject_AsVoidPtr(sip_capiobj));
	}
SIP_UNBLOCK_THREADS
	return api;
}

sipExportedModuleDef * getSipModule( const char * name )
{
	const sipAPIDef * api = getSipAPI();
	if( !api ) return 0;

	sipExportedModuleDef * module = api->api_find_module( name );
	if( !module )
		LOG_5( "getSipModule: Unable to lookup module " + QString::fromLatin1(name) + " using api_find_module" );
	return module;
}

sipWrapperType * getSipWrapperType( const char * module_name, const char * typeName )
{
	sipExportedModuleDef * module = getSipModule(module_name);
	if( !module ) return 0;

	for( int i = module->em_nrtypes - 1; i >= 0; i-- ) {
		sipWrapperType * swt = module->em_types[i];
		sipTypeDef * type = swt->type;
		if( strcmp( type->td_name, typeName ) == 0 || ( type->td_cname && strcmp( type->td_cname, typeName ) == 0 ) )
			return swt;
	}

	LOG_5( "getSipWrapperType: Unabled to find " + QString::fromLatin1(typeName) + " in module " + QString::fromLatin1(module_name) );
	return 0;
}

static sipWrapperType * sipQVariantWrapper()
{ static sipWrapperType * sQVariantW = 0; if( !sQVariantW ) sQVariantW = getSipWrapperType("PyQt4.QtCore","QtCore.QVariant"); return sQVariantW; }

void * pythonMetaTypeCtor( const void * copy )
{
	if( copy ) {
		SIP_BLOCK_THREADS
		Py_INCREF( (PyObject*)copy );
		SIP_UNBLOCK_THREADS
		return const_cast(copy);
	}
	return 0;
}

void pythonMetaTypeDtor( void * pyObject )
{
	SIP_BLOCK_THREADS
	Py_DECREF((PyObject*)pyObject);
	SIP_UNBLOCK_THREADS
}

int registerPythonQMetaType( PyObject * type )
{
	int ret = 0;
	PyObject * pyname = PyObject_GetAttrString( type, "__name__" );
	if( !pyname ) {
		printf( "registerPythonQMetaType: Unabled to get attribute __name__\n" );
		return ret;
	}
	const char * typeName = PyString_AsString(pyname);
	if( typeName ) {
		ret = QMetaType::registerType( typeName, reinterpret_cast(pythonMetaTypeDtor), reinterpret_cast(pythonMetaTypeCtor) );
		// Dont return success when it's returning an already registered builtin type
		if( ret < QMetaType::User ) ret = 0;
	} else
		printf("registerPythonQMetaType: __name__ attribute is not a string\n");
	Py_DE

Re: [PyQt] Construct QVariant from object of user type

2008-04-16 Thread Matt Newell
On Wednesday 16 April 2008 14:18:26 Arve Knudsen wrote:
> On Wed, Apr 16, 2008 at 11:33 AM, Phil Thompson
>
> <[EMAIL PROTECTED]> wrote:
> > On Wednesday 16 April 2008, Arve Knudsen wrote:
> >  > Phil, any comment on this?
> >  >
> >  > Thanks,
> >  > Arve
> >
> >  Unless you can use the ctor that takes a void* I don't see how you can
> > expect to extend the functionality of a C++ class from Python.
>
> How am I supposed to use the QVariant(int typeOrUserType, const void*
> copy) constructor from Python? The documentation refers to
> sip.voidptr, which I know nothing about, and  to use qVariantFromValue
> which isn't defined.
>
> I need to store objects of a custom class in QVariants, with a certain
> type code (QVariant::Type). The reason I need to do this is that
> QItemEditorFactory is parameterized on QVariant::Type.
>
> Arve


If you look at qmetatype.h, you'll see that it should be possible to create a 
mechanism to register custom python classes as QVariant types.  You just need 
to implement Constructor/Destructor methods that call Py_INCREF/Py_DECREF. 
Then for each custom python type call QMetaType::registerType(...).  This 
would need to be implemented in c++ with a python interface.

You could then write a custom QVariant constructor that detects if the python 
object's type is registered, and automatically call the QVariant(int 
type,void*) ctor, or throws an exception for non-registered types.

BTW, you don't really have to use QItemEditorFactory.  You can use a custom 
delegate.  Of course you still have to return the data as a QVariant unless 
you go around the QModelIndex::data function, but that would probably tie the 
delegate to the model, which might defeat the purpose.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] PyQt-based Tetr*s

2008-03-25 Thread Matt Newell
On Tuesday 25 March 2008 16:29:36 Joshua Bronson wrote:
> I am new to Qt, and I just whipped up a PyQt-based implementation of
> Tetr*s. I am getting quite a bit of padding between the edges of the window
> and the edges of the area in which the blocks are drawn, and I can't seem
> to figure out how to set this to zero.
> To see this, svn export the following files:
> http://aipytris.googlecode.com/svn/trunk/aipytris/g.py
> http://aipytris.googlecode.com/svn/trunk/aipytris/piece.py
> http://aipytris.googlecode.com/svn/trunk/aipytris/observable.py
> http://aipytris.googlecode.com/svn/trunk/aipytris/boardqt.py
>
> Then run boardqt.py.
>
> Does anyone know how to get rid of this padding?
>
> Thanks,
> Josh

Call setMargin( pixels ) on your layout.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QTableModel (custom) with QComboBox in a cell... (take 2)

2008-03-19 Thread Matt Newell
On Wednesday 19 March 2008 00:43:46 Dirk Wagener wrote:
> Hi
> I sent this before, but got no replies.
> Here we go again:
>
> I am implementing a custom model for a table view. I have an editable cell
> in which the user can enter a value. What I want to do is to make the cell
> a QComboBox so that the user can enter a text value for the cell OR select
> some value from a drop-down list. I am not using delegates currently.
> What is the correct (easiest) way to achieve this?
>

You either need to write a custom delegate class or a QItemEditorFactory 
class.  I've never used the QItemEditorFactor, i've just used custom 
delegates.

You'll need to implement createEditor, setModelData, and setEditorData.  You 
can pass your data from the model as a qstringlist, or any custom type 
wrapped as a QVariant(You can even use your own roles if needed). For example 
you could pass a QStringList for the editor role and QString for the Display 
role to use as the current value, which would give you enough info to fill in 
a combo box.

Make sure to call setItemDelegate on the view, passing your custom delegate 
class.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Signal on Selection in QTreeView

2008-03-18 Thread Matt Newell
On Tuesday 18 March 2008 10:52:20 Matt Newell wrote:
> On Tuesday 18 March 2008 09:46:06 [EMAIL PROTECTED] wrote:
> > Phil/Andreas,
> >
> >  I've been experimenting again using some of the recommendations and
> > some examples I have found.   Please look at the new example I am working
> > with, which is below.
> >
> > I can now have a reaction to a selected item in a list.  When
> > something is selected, the 'slot' function is called and is run.  Great! 
> >  In this case it prints out some details including the number of rows,
> > etc.
> >
> > Now I am still trying to access a reference to the selected item so I
> > can pull the data from the original list and display it elsewhere in a
> > different widget.  The original author of this modified program included
> > a function call called "data".   However, I cannot figure out how to use
> > it. I guess my hangup is the index and role fields.  I don't know what to
> > put in those fields to get the currently selected item.
> >
> > In my case I need the current row, that is the current row number.  I
> > don't need to fiddle around with the row entries as I already have them
> > in the original list.
> >
> >Could someone help me write a simple function called
> > "get_current_row_number", which returns an integer indicating the
> > highlighted row?
> >
> > Kevin
>
> You just need to get the QModelIndexes from the QItemSelection 'selected'
> object in your slot, then call row() on them.
>
> The QItemSelection is a list of QItemSelectionRange objects.  Each
> QItemSelectionRange contains 1 or more selected QModelIndexes, represented
> from a topleft to bottom right with the same parent.
>
> > def slot(self, selected, deselected):
>
>   # this will give you an index for each row and col
>   # so if you have multiple columns selected you will get duplicates
>   for idx in selected.indexes():
>   print idx.row()
>   # Here is how to get the rows even if there are multiple columns 
> selected
>   # This ignores the indexes' parents, which is fine if your
>   # model is 2 dimensional
>   for selectionRange in selected:
>   for i in
> range(selectionRange.topLeft().row(),selectionRange.bottomRight().row()):
>   print "Row %i selected" % i
>

Sorry, that last part should be - 
for i in range(selectionRange.top(),selectionRange.bottom() + 
1):
print "Row %i selected" % i


>
> Matt
> ___
> PyQt mailing listPyQt@riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt


___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Signal on Selection in QTreeView

2008-03-18 Thread Matt Newell
On Tuesday 18 March 2008 09:46:06 [EMAIL PROTECTED] wrote:
> Phil/Andreas,
>
>  I've been experimenting again using some of the recommendations and
> some examples I have found.   Please look at the new example I am working
> with, which is below.
>
> I can now have a reaction to a selected item in a list.  When something
> is selected, the 'slot' function is called and is run.  Great!   In this
> case it prints out some details including the number of rows, etc.
>
> Now I am still trying to access a reference to the selected item so I
> can pull the data from the original list and display it elsewhere in a
> different widget.  The original author of this modified program included a
> function call called "data".   However, I cannot figure out how to use it. 
> I guess my hangup is the index and role fields.  I don't know what to put
> in those fields to get the currently selected item.
>
> In my case I need the current row, that is the current row number.  I
> don't need to fiddle around with the row entries as I already have them in
> the original list.
>
>Could someone help me write a simple function called
> "get_current_row_number", which returns an integer indicating the
> highlighted row?
>
> Kevin
>

You just need to get the QModelIndexes from the QItemSelection 'selected' 
object in your slot, then call row() on them.

The QItemSelection is a list of QItemSelectionRange objects.  Each 
QItemSelectionRange contains 1 or more selected QModelIndexes, represented 
from a topleft to bottom right with the same parent.

> def slot(self, selected, deselected):
# this will give you an index for each row and col
# so if you have multiple columns selected you will get duplicates
for idx in selected.indexes():
print idx.row()
# Here is how to get the rows even if there are multiple columns 
selected
# This ignores the indexes' parents, which is fine if your
# model is 2 dimensional
for selectionRange in selected:
for i in 
range(selectionRange.topLeft().row(),selectionRange.bottomRight().row()):
print "Row %i selected" % i


Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] PyQt

2008-03-05 Thread Matt Newell
On Wednesday 05 March 2008 15:58:26 Jon Chambers wrote:
> Hi,
> I'm trying to write a program that creates an onscreen keyboard that uses
> an 2-analogue stick joypad for input. I'm having issues becuase the
> joystick needs to be polled regularly. I'm using a QTimer  to call a
> paintEvent update()  that polls the joystick in the main class (Keyboard).
> However there's some other drawing i want to do when the joystick is
> polled. However the drawing is supposed to be done by a different class
> with its own graphics etc (called Ring), and i found the only way that
> seemed to work was to put the drawing i want to do in the paintEvent of
> that class and both seem to get called. But this seems kinda weird, and for
> some reason if i simply called the drawing to be done by Ring as a method
> of the Ring object in the paintEvent of Keyboard it doesn't work.
> I'm sorry if there's a bit confusing, i'm very new to programming and QT
> and also asking questions on mailing lists.
>


I think the correct thing to do would have a slot connected to the timer that 
polls the joystick then calls ring.update().  You should generally avoid 
having any code in the paintEvent except for actual painting code.  And you 
should call paintEvent on the widget that actually needs repainting.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Model/View with multiple thread

2008-02-08 Thread Matt Newell
On Thursday 07 February 2008 23:49:26 Sebastian Vetter wrote:
> Hallo everyone,
>
> I've started working with the Model/View concept and have some questions
> on implementing it in a multithreading environment. I hope that some of
> you have some ideas or advice on that and I'll highly appreciate any!
>
> So that's the basic structure: I'm working on an application that's
> processing data in a spreadsheet class. All processing in done in a
> separate thread and communicates with the GUI thread through multiple
> signals and slots. I now implemented a model in the GUI thread handling
> the exact same spreadsheet object, since the Model and View have to live
> in the same thread (is that right?).

Yes, you really want to keep all usage and updating of your model in the same 
thread as the view(s).

>
> Thinking about how to keep the spreadsheet objects in worker and main
> thread synchronised I came up with two ideas:
>
> 1. Using signals and slots in both the worker and the model to update
> their spreadsheet objects whenever the other one changes.
>
> 2. Using a thread-safe singleton of the model to handle one single
> instance of the spreadsheet that are used in both threads.
>
> What would be considered a 'better' solution? Is there any other
> alternative that might work even better?
>
> I really appreciate any thoughts on this. Thanks in advance.
>

The easiest way to update your model would be to use Queued signals from the 
worker thread to the gui thread(Queued is the default when connecting an 
object's signal to another object's slot that lives in a different thread).  
An alternative would be to use custom QEvents delivered to the model via the 
gui thread's event queue.

As for delivering updates from the model back to the work, you are probably 
best off using the same methods as above.  

Matt



___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] qtreeview display speed

2008-02-04 Thread Matt Newell
On Monday 04 February 2008 08:52:44 Baba-k wrote:
> Hi everyone,
>
> I'm relatively new to pyqt and am encountering some problems while trying
> to make a custom tree widget (using the model/view classes) that i was
> hoping some one here might be able to help me with.
>
> Ive made a custom treewidget which is using a custom view and model. The
> view is a subclass of QTreeView and the model a subclass of
> QAbstractItemView. The model class takes its data in the form of a custom
> item class. Both the custom model and item classes are very similar to the
> examples in the docs just with some extra functionality where needed. The
> model and view classes are being used in a custom QWidget which is inside a
> QDialog.
>
> The tree is designed to show the difference between two hierarchies of
> data, the size of these hierarchies can vary. Before calling the 'show'
> method of the QDialog object, the items inside the tree are expanded.
> The problem I'm having is that when displaying fairly large hierarchies
> (7000+ rows) it can take onwards of 10mins for the contents of the widget
> to be drawn. If I don't expand the items in the tree before calling 'show'
> the it is pretty much instant. Has anyone experienced anything like this
> before ??
>
> Any ideas or suggestions about this would be very much appreciated :)
>
> thanks alot
>  babak

Which version of qt are you using?  Each expanded item is (internally) stored 
as a qpmi(QPersistentModelIndex).  With Qt versions < 4.3.0, creating each 
qpmi is an O(n) operation, where n is the number of existing qpmis.  Since 
you are expanding all the items in the view, that results in an O(n^2) 
operation.

With qt >= 4.3.0, qpmi creation is O(log n), since they are stored in a sorted 
list, and a binary search is used to find/create the new qpmi.  With your 
code, this would result in total complexity of O(n log n), quite an 
improvement.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] __gettattr__/__setattr__ special method support

2008-01-09 Thread Matt Newell
Is there a specific reason that sip doesn't support __gettattr__ and 
__setattr__ special methods?  Or does it and i'm just missing something?


Thanks,
Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QSqlQuery Error

2007-11-01 Thread Matt Newell
On Thursday 01 November 2007 08:14, Linos wrote:
> Hello,
> queryinsertmaxdb = QSqlQuery(maxdb)
> queryinsertmaxdb.prepare("INSERT INTO NAMESPACE.MODELO_FAMILIA (FAMILIA_ID,
> NOMBRE, SECCION) VALUES (?, ?, ?)")
>

I think you should try creating the QSqlQuery and the prepare inside the loop.  
If everything works fine then report the bug to trolltech.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] Does sip support using.

2007-09-20 Thread Matt Newell
Does sip support using keyword as in the following

class A
{
public:
void a();
void a(int);
};

class B : public A
{
public:
using A::a;
void a(int);
}


so you can call - 

o = B()
o.a()


You can achieve the same by declaring B as
class B : public A
{
public:
void a();
void a(int);
}

but then it's out of sync with the header file and often adds a lot of extra 
for some classes.

Sip barfed when I tried it, but I haven't upgraded in a while. 

If it's not implemented and not something you want to take the time to do atm, 
then I would consider writing a patch if you think it'll be accepted.

Thanks
Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QTreeView access violation

2007-09-14 Thread Matt Newell
On Thursday 13 September 2007 01:53, Dirk Wagener wrote:
> Hi
>
> I have the following problem when performing the following steps in
> sequence:
>
> * I have a QTreeView using a custom model.
> * I expand a node that contains a bunch of items.
> * I select one of the items (children) by clicking on it.
> * I then edit the name of the item in-place (custom setData()
> implementation).
> * I signal a dataChanged() event.
> * I send a signal from somewhere else that the parent must be refreshed.
> * The parent removes all its children (removeRows()) and re-populates.
> * CRASH!! (only sporadically)
>Qt gives my one of these:
>...
> I am not 100% sure about this, but it seems to have something to do with
> the fact that a selected item gets removed.
> If I call clearSelection() before removing the rows, the violation does
> not happen! This feels like a bit of a hack. What is the
> correct way to handle this?
>
> Kind regards
> Dirk

What Qt version are you using? This may be a known Qt bug that was fixed.  

Are you calling beginRemoveRows/endRemoveRows with the proper values?

It's best to avoid removing and re-adding rows if you can(assuming the rows 
that are re-added are the same contents), so that selections and state are 
preserved.  Instead just update the data of the changed rows, add new rows, 
and delete old rows.

It also sounds like you are removing the rows from inside the dataChanged 
signal, instead of letting the stack unwind first.  You could fire 
the "parent must be refreshed." signal using a single shot timer, that could 
fix the problem.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Forcing stacktrace in program

2007-09-14 Thread Matt Newell
On Friday 14 September 2007 07:14, Arve Knudsen wrote:
> I want to be able to get a stack trace of my hanging PyQt application, does
> anyone have any tips on how this can be done in a cross-platform way? I can
> catch SIGINT (and then write the trace before quitting) but the program
> isn't necessarily run in a terminal, so I need some way of killing it from
> the GUI (e.g., End Task on Windows). I have no idea how to catch the event
> resulting from say End Task on Windows however. Any practical insight would
> be very welcome.
>
DrMingw might be able to help.  I don't know if it can catch a kill event, but 
it'll log a stack trace to a file if your program crashes.  You can probably 
hack it to also log when your program is killed.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Hijacking QtCore.connect, disconnect and emit

2007-07-12 Thread Matt Newell
On Thursday 12 July 2007 14:40, Carlos Scheidegger wrote:
> Hello,
>
>   I am a developer of a largish (~75kloc) application that uses PyQt, and
> I'm trying to track down a bug that might be related to signal handling. I
> was hoping to be able to track down every signal that is emitted, even if
> that makes everything superslow while debugging. I have managed to hijack
> PyQt's connect and disconnect calls by a seriously horrible hack:
>
> _oldConnect = QtCore.QObject.connect
> _oldDisconnect = QtCore.QObject.disconnect
>
> def _wrapConnect(callableObject):
> """Returns a wrapped call to the old version of
> QtCore.QObject.connect""" @staticmethod
> def call(*args):
> callableObject(*args)
> _oldConnect(*args)
> return call
>
> def _wrapDisconnect(callableObject):
> """Returns a wrapped call to the old version of
> QtCore.QObject.disconnect""" @staticmethod
> def call(*args):
> callableObject(*args)
> _oldDisconnect(*args)
> return call
>
> def enableSignalDebugging(**kwargs):
> """Call this to enable Qt Signal debugging. This will trap all
> connect, and disconnect calls."""
>
> f = lambda *args: None
> connectCall = kwargs.get('connectCall', f)
> disconnectCall = kwargs.get('disconnectCall', f)
> emitCall = kwargs.get('emitCall', f)
>
> def printIt(msg):
> def call(*args):
> print msg, args
> return call
> QtCore.QObject.connect = _wrapConnect(connectCall)
> QtCore.QObject.disconnect = _wrapDisconnect(disconnectCall)
>
> Strangely enough, this works. However, the direct extension of the trick to
> QtCore.emit does not. Is there some anything I can do (even if it is
> similarly hideous) to hijack the call to emit?
>
> We're currently using PyQt 4.1, sip 4.5.
>
> Thanks a lot in advance,
> -carlos

Qt has builtin callbacks for signal slot debugging.  I think you could use 
python's ctypes module to create python callbacks that would work.  I don't 
have much experience with ctypes or using Qt's callbacks, so I can't provide 
any further details.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] QVector usage

2007-05-17 Thread Matt Newell
On Thursday 17 May 2007 13:02, Jason Hihn wrote:
> I've gotten around the form builder problem for now, but I ran into another
> problem.
>
> I have the following function:
>
> E3PLAY_API bool play_list_from_file(const QString &fname,
> QVector &play_list);
>
>
>
> Where fname is an in, and play_list is an out. (The file is parsed and
> returns a qvector of play list items.) On return from the function, it is
> supposed to return an array (qvector) of the items in the file.
>
>
>
> How can I get this function to work as it does in C++?
>
>
I'm not sure if sip handles this automatically, but i think in python you'll 
want it to return a tuple containing (returnValue, play_list).

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Database Connection still does not work...

2007-05-07 Thread Matt Newell

>
> Hi again,
>
> I finally managed to successfully build Qt with makefiles and have now
> libqsqlpsql.dll in plugin directory. I have also set environmentvariables
> (as I don't have admin rights on my PC here at work, I always run this
> batch file in cmd shell:
>
> set Path=C:\Bin;C:\Bat;C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem;
> C:\python25;C:\Qt\4.2.3\bin;C:\PyQt4.2\;C:\Programme\qgistrunk;C:\mingw\bin
>;
> C:\Programme\PostgreSQL\8.2;C:\cmake\bin;C:\mingw\include;C:\Programme\Post
>greSQL\8.2 set PGLIB=C:\Programme\PostgreSQL\8.2\lib
> set PGINCLUDE=C:\Programme\PostgreSQL\8.2\include
> set PGBIN=C:\Programme\PostgreSQL\8.2\bin
> set PGDATA=C:\Programme\PostgreSQL\8.2\data
> set PGUSER=postgres
> set QT_DEBUG_PLUGINS=1
>
> when I then run Python from shell and just want to test if it's possible to  
creat a connection, the same errormessage occured...:
> > >from PyQt4.QtSql import *
> >
> > QSqlDatabase.addDatabase("QPSQL")
> >
> > in Python Interpreter, then the error-message "QSqlDatabase: driver not
> > loaded
> > QSqlDatabase:
> > available drivers
> >  PyQt4.QtSql.QSqlDatabase object at 0x008E58A0"
>
> So, I really don't know what goes wrong with this...
>
> Would be so great, if anyone can help me to step forward with this stuff
> :-)
>
> Thanks in advance,
> Marion.


Would you please paste the python code you are using to connect to the 
database. 

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] Database Connection

2007-05-04 Thread Matt Newell
On Friday 04 May 2007 06:14, [EMAIL PROTECTED] wrote:
> Hello list,
>
> I'm quite new to Python and PyQt. So I would be very thankful, if anyone
> could help me with my starting problems...
>
> I'm planning to write some Python Plugins for QuantumGIS. The function of
> those Plugins should be to connect to a PostgreSQL/PostGIS Database and
> commit SQL-Queries, which in return should export Data through a form
> (written to a comma seperated textfile).
> Does anyone know, if there are any scripting-examples dealing with that or
> a similar problem, just to get a clou
>
> I'm now experimenting with QtSql Classes, but every try to connect to my
> database, explained in PyQt's Class reference documentation fails... (I
> tried with Python interpreter shell)
>
> Thanks for every given hint...!
>
> greets,
> Marion

Have you been able to successfully connect to the database via pgadmin or 
another tool from the same machine?  What's the error message you get when 
the connect fails(QSqlDatabase.lastError().text())?

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] A Qt error pushed me out of Python

2007-04-13 Thread Matt Newell
On Friday 13 April 2007 09:43, Gerard Vermeulen wrote:
> If you are using a version of PyQt before 4.2, you cannot really use
> PyQt widgets like this because they do not respond to events, since
> their is no event loop (you did not call yourQApplication._exec()).
> PyQwt has a module 'iqt' that fakes an event loop in combination with
> the readline module, see
> http://pyqwt.sourceforge.net/doc5/iqt-intro.html
>
> I think that PyQt-4.2 has also half the facility of faking the event
> loop: you still have to use the readline module (this is what I think,
> I did not test it) to make sure that events are handled.
>
> Anyhow, if you want to use PyQt from the interpreter, I recommend
> the use of a Python startup file as explained in iqt-intro.html.
>
> Regards -- Gerard
> ___
> PyQt mailing list[EMAIL PROTECTED]
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt


You don't need to call QApplication::exec to have an event loop.  A local 
event loop is created automatically whenever you call QMenu::exec, 
QDialog::exec or one of the static QMessageBox methods.  You still need a 
QApplication of course.

Try this to see

from PyQt4 import QtGui
import sys
app = QtGui.QApplication(sys.argv)
QMessageBox.critical(None,"Hello","World")

control returns to the caller after the message box is closed.

Matt

___
PyQt mailing list[EMAIL PROTECTED]
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyQt] qtrc? other options?

2007-03-23 Thread Matt Newell
On Friday 23 March 2007 08:45, Kerri Reno wrote:
> I'm trying to set up my application to run on the server with a very
> thin client.  I want only my window to show, not a wrapping window.
> I've been trying to make this work with NX from www.nomachine.com.  It
> does run my application, without a surrounding window, but where it's
> getting the theme or style from, I don't know.  It's rather ugly.  (I've
> got my application set to the 'cleanlooks' style, but there's no place I
> can see to change the colors.  It comes up medium gray with highlighting
> in dark blue).  I tried setting up a qtrc file, then I found that QT4
> doesn't use qtrc.  I can get a nice looking theme/style, but I have to
> have a window manager running, which sets up either a desktop or
> surrounding window.
>
> Does anyone have any experience with this, and can point me in the right
> direction?
>
> Kerri

Try calling QApplication.setPalette(...) with a palette of your choosing.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


[PyQt] Re: [PyKDE] PyQt 4 doesn't allow to create an application, given an already open display. How to solve it?

2007-03-08 Thread Matt Newell
On Thursday 08 March 2007 01:11, Phil Thompson wrote:
> On Thursday 08 March 2007 8:40 am, Matt Newell wrote:
> > On Thursday 08 March 2007 00:07, Ulrich Berning wrote:
> > > [EMAIL PROTECTED] wrote:
> > > >Eh, I have just realized that I have replied directly to Phil
> > > > Thompson, not to this list (this is because I have used unfamiliar
> > > > webmail client). So this is our conversation:
> > > >
> > > >*** Me: ***
> > > >You can look at that example by Zack Rusin, it is very simple, here is
> > > > code: http://ktown.kde.org/~zrusin/examples/argb.tar.bz2 (look at
> > > > main.cpp)
> > > >
> > > >That Display instance come directly from xlib, it is created by
> > > > XOpenDisplay: http://lxr.freedesktop.org/ident?i=XOpenDisplay
> > > >
> > > >In Python, I am using ctypes module to directly access xlib (libX11)
> > > >and call XOpenDisplay.
> > > >
> > > >*** Phil: ***
> > > >I meant, in the context of PyQt. PyQt needs to know about the type.
> > > >
> > > >*** Me: ***
> > > >I can't help you much in this, I don't know much about ctypes, I have
> > > > only learned it because I want to create ARGB windows with PyQt (and
> > > > then I realized that I can't do it because PyQt doesn't support it).
> > > > But you can try this code:
> > > >
> > > >### Python code ###
> > > >import ctypes
> > > >
> > > >class Display(ctypes.Structure):
> > > >pass
> > > >
> > > >xlib = ctypes.CDLL('libX11.so.6')
> > > >xlib.XOpenDisplay.restype = ctypes.POINTER(Display)
> > > >xlib.XOpenDisplay.argtypes = [ctypes.c_char_p]
> > > >
> > > >display = xlib.XOpenDisplay(':0.0')
> > > >### End of Python code ###
> > > >
> > > >This will create 'display' object, which is pointer to 'Display'
> > > > structure (which is derived from standard ctypes.Structure).
> > > >
> > > >But this is all I can tell you, as I said I don't know any details
> > > > about this process, only that it works (I have tried creating window
> > > > with pure xlib).
> > > >
> > > >Ctypes are standard module in python 2.5 (for Python 2.4 it is
> > > > external module), so I think PyQt should support it.
> > >
> > > The ctypes extension doesn't build on AIX, HP-UX, IRIX and Solaris.
> > > With some changes, it may build on IRIX and Solaris, because libffi has
> > > been ported to these platforms. On AIX and HP-UX, you have definitely
> > > lost. I've never understood, why ctypes became a standard module.
> > >
> > > PyQt works on the above platforms. Making it dependent on the ctypes
> > > extension seems to be a bad idea.
> >
> > Display is just a pointer.  I think PyQt could support accepting a ctypes
> > pointer as an arguement without depending on ctypes being available.  The
> > ctypes pointer is simply passed as a PyObject * and regular python api
> > calls are used to check that it is indeed a ctypes pointer, and to get
> > the value.
>
> Ironically ctypes doesn't provide the necessary C API to do this. However
> if (in Python) you can get the address of the real data structure as a
> number (ctypes.addressof() ?) then you can create a sip.voidptr from it and
> I can add the ctors to accept that.
>


import ctypes
import sip

class Display(ctypes.Structure):
pass

xlib = ctypes.CDLL('libX11.so.6')
xlib.XOpenDisplay.restype = ctypes.POINTER(Display)
xlib.XOpenDisplay.argtypes = [ctypes.c_char_p]

display = xlib.XOpenDisplay(':0.0')

dvp = ctypes.cast(display,ctypes.c_void_p)
print dvp.value
svp = sip.voidptr(dvp.value)
print int(svp)


I think the same thing could also be accomplished entirely in c++, not sure if 
it would be worth it.

Matt
___
PyQt mailing listPyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt


Re: [PyKDE] PyQt 4 doesn't allow to create an application, given an already open display. How to solve it?

2007-03-08 Thread Matt Newell
On Thursday 08 March 2007 00:07, Ulrich Berning wrote:
> [EMAIL PROTECTED] wrote:
> >Eh, I have just realized that I have replied directly to Phil Thompson,
> > not to this list (this is because I have used unfamiliar webmail client).
> > So this is our conversation:
> >
> >*** Me: ***
> >You can look at that example by Zack Rusin, it is very simple, here is
> > code: http://ktown.kde.org/~zrusin/examples/argb.tar.bz2 (look at
> > main.cpp)
> >
> >That Display instance come directly from xlib, it is created by
> > XOpenDisplay: http://lxr.freedesktop.org/ident?i=XOpenDisplay
> >
> >In Python, I am using ctypes module to directly access xlib (libX11)
> >and call XOpenDisplay.
> >
> >*** Phil: ***
> >I meant, in the context of PyQt. PyQt needs to know about the type.
> >
> >*** Me: ***
> >I can't help you much in this, I don't know much about ctypes, I have only
> > learned it because I want to create ARGB windows with PyQt (and then I
> > realized that I can't do it because PyQt doesn't support it). But you can
> > try this code:
> >
> >### Python code ###
> >import ctypes
> >
> >class Display(ctypes.Structure):
> >pass
> >
> >xlib = ctypes.CDLL('libX11.so.6')
> >xlib.XOpenDisplay.restype = ctypes.POINTER(Display)
> >xlib.XOpenDisplay.argtypes = [ctypes.c_char_p]
> >
> >display = xlib.XOpenDisplay(':0.0')
> >### End of Python code ###
> >
> >This will create 'display' object, which is pointer to 'Display' structure
> >(which is derived from standard ctypes.Structure).
> >
> >But this is all I can tell you, as I said I don't know any details about
> > this process, only that it works (I have tried creating window with pure
> > xlib).
> >
> >Ctypes are standard module in python 2.5 (for Python 2.4 it is external
> >module), so I think PyQt should support it.
>
> The ctypes extension doesn't build on AIX, HP-UX, IRIX and Solaris. With
> some changes, it may build on IRIX and Solaris, because libffi has been
> ported to these platforms. On AIX and HP-UX, you have definitely lost.
> I've never understood, why ctypes became a standard module.
>
> PyQt works on the above platforms. Making it dependent on the ctypes
> extension seems to be a bad idea.
>

Display is just a pointer.  I think PyQt could support accepting a ctypes 
pointer as an arguement without depending on ctypes being available.  The 
ctypes pointer is simply passed as a PyObject * and regular python api calls 
are used to check that it is indeed a ctypes pointer, and to get the value.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Can I creat a widget which can click and has a erose edge?

2007-03-07 Thread Matt Newell
On Wednesday 07 March 2007 02:08, Marco wrote:
> A QFrame seem can set a un-normal edge, but how to let it clickable?
>

import PyQt4.QtGui

class ClickableFrame( PyQt4.QtGui.QFrame ):
def __init__(self,parent=None):
PyQt4.QtGui.QFrame.__init__(self,parent)

def mouseReleaseEvent( self, event ):
print "Clicked!"


or if you want all the QPushButton stuff(clicked signals, etc), you could 
override the paintEvent, and just call PyQt4.QtGui.QFrame.paintEvent(self, 
event), so that it is drawn like a normal frame.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] more and more signal from on connect...(on QProcess)

2007-03-05 Thread Matt Newell
On Monday 05 March 2007 23:42, Marco wrote:
> Hi, I want to write a MPlayer GUI frontend.
>
> Now, I meet a bug, when:
> click "play", a movie showing, click "stop", the movie stop and print
> ONE message
>
> click "play", the movie show again, click "stop", the movie stop and
> print TWO messages
>
> click "play", the movie show again, click "stop", the movie stop and
> print THREE messages
>
You are connecting multiple times.  Move your connect calls to the __init__ 
method(after you create the proc of course).

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Crashing problems, suggestions?

2007-03-01 Thread Matt Newell
On Thursday 01 March 2007 12:36, Kevin Cureton wrote:
> Since I converted my application from PyQt3 to PyQt4, I've run into
> some issues with the threading.
>
> I ran into the deadlock problems a while back and managed to avoid it
> by only sending signals from QThreads to the main thread. The main
> thread, instead of sending signals or events to the QThreads, would
> instead hand them work via a thread-safe queue I wrote. Doing that
> avoided the deadlock problem but appeared to uncover another issue.
> Consistent crashes.
>
> I'm not going to claim this is a PyQt or Qt issue. It could very well
> be my failure to protect some resource with a mutex. However, after
> various attempts over the past month, I need to take some focused
> time and resolve this issue. I've attached a crash trace. We are
> running the application on both Mac and Linux and similar results
> (though I don't have a Linux trace available currently).
>
> I'm looking for some ideas on how to approach debugging this problem
> (or web pages that can help). I'm hoping to create a small, scoped
> test case that demonstrates this problem and get that sent to the
> list. Until then, any ideas or thoughts on how to proceed would be
> greatly appreciated.
>
> I am currently running Qt 4.2.2, and the sip and PyQT4 snapshots from
> 20070227 on both a Powerbook (PPC, 10.4.8) and a Mac Pro (Intel,
> 10.4.8).
>
> --kev
>


What kind of data structures are you using in your worker thread?  I was 
having some stability issues with implicitly shared( via reference counting ) 
database classes that were being loaded in a worker thread.  I was able to 
fix them by using QBasicAtomic instead of an int for reference counting.  May 
not be at all relevant to your situation, but something to think about.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Threading and multiple processors, any change?

2007-03-01 Thread Matt Newell
On Thursday 01 March 2007 03:16, Phil Thompson wrote:
> On Thursday 01 March 2007 10:47 am, V. Armando Sole wrote:
> > Hello,
> >
> > I just have a simple question (that does not imply a simple answer).
> >
> > With all the new options/possibilities recently discussed concerning the
> > GIL handling, is it possible to profit of multiple processors in Python
> > using QThreads thru PyQt4?
>
If a large amount of the time is spent in C++(Qt, or your own custom sip 
modules), then yes, it should allow more concurrency.  Already using QThreads 
could be a big win if the threads spend time blocking on IO or other 
operations that already released the GIL.

> The issues of a single GIL haven't gone away. The only difference is that
> the GIL is (probably) released much more frequently than it was before. The
> changes are to do with correctness (specifically deadlock avoidance) rather
> than performance.
>
> I don't know what the performance effect would be on a multi-processor.
> Matt said that he could run more threads but I don't know what hardware he
> has. I noticed a (small) degradation on my uni-processor - as would be
> expected.
I'm running a dual proc, single core xeon(3.06Ghz), so it would make sense 
that I gained a bit of performance, though it was only my impression.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-26 Thread Matt Newell
> >
> > It seems that I need to work out how to find the thread affinity of a
> > Python object...
>
> ...which doesn't seem possible. So I think it's a case of clarifying the
> documentation...
>
Shouldn't this be possible for python callable's that are members of a QObject 
derived python class?  

> If you connect to a SLOT() then the slot is executed in the thread as
> described in the Qt documentation.
>
> If you connect to a Python callable then the slot is executed according to
> the same rules with the additional proviso that a SLOT is created on the
> fly in the thread in which the call to connect() is made.
If the slot(python callable) is a member of a python class that is derived 
from QObject, then the PyQtProxy object created should then be moved to the 
same thread that the QObject is in, using QObject::moveToThread.  That way 
the slot is called in the same thread as the QObject, which follow the same 
behavior as qt.  The only exception will be when a python callable that is 
not a member of a QObject derived class is used, then it will be called in 
whatever thread the connect call is made.

> You can then get your sample-thread example working by either moving the
> connect() call to the __init__() method, or by making the connection a
> direct one (or an auto one). In the first case the slot will execute in the
> main thread, and in the second it will execute in the sub-thread. As the
> slot is updating the GUI then you want to do the former.
>
> Matt - does this explanation still mean that the GIL needs to be released
> in QObject ctors etc? Or have I got 2 separate issues confused?
>
They are 2 separate issues, but after reviewing the relevant qt code I'm not 
sure if it will be required to release the GIL for qobject ctors/dtors.  It 
may work to require the GIL to be *LOCKED* whenever calling qt code that can 
hold a qt lock while calling back into python code(emit calling 
qmetatype::construct is currently the only place I know of).  

I'm still not 100% sure about all this though, and I think there may be a way 
to eliminate the deadlock situation by a simple change to the qt code.  I 
need more time to think about it, it kind of makes my head hurt:)

Matt
> Phil
>
> ___
> PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
> http://mats.imk.fraunhofer.de/mailman/listinfo/pykde

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-26 Thread Matt Newell
On Saturday 24 February 2007 11:58, Michael Guntsche wrote:
> On Feb 24, 2007, at 10:28, Phil Thompson wrote:
> > In the meantime you could try changing PyQt's configure.py (in
> > set_sip_flags()) so that it invokes sip with the -g flag.
>
> I did some more tests and noticed something weird I do not quite
> understand.
> I once again took my trusty test script and created two different
> versions.
>
> Version 1 (old version):
>
> self.connect(self, QtCore.SIGNAL("steip(const QString &)"),
> self.container.write)
>
> Is called in the threads run()-method.
> Same old behaviour, after adding some more threads the program hangs
> and later dies.
>
> If I try to use a QueuedConnection nothing gets printed at all. Has
> this something to to with the per thread eventloop,
> I do not understand this behaviour at all.
>
This works fine for me.  Either leaving the connection type 
blank(AutoConnection), or specifying QueuedConnection results in the exact 
same behavior.  This is with the latest sip/pyqt snapshot as of friday.

> Version 2:
>
> self.connect(s, QtCore.SIGNAL("steip(const QString &)"),
> self.write,QtCore.Qt.QueuedConnection)
>
> Is called in the main thread after creating the thread (s).
> In this case the QueuedConnection works and I see that my textEdit
> field gets filled.
> Furthermore I can create a lot more threads (over 100), can kill and
> recreate them without any problems at all.
This makes sense that it would reduce the number of deadlocks, since there's 
less code paths being executed in the threads that can cause a deadlock.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-26 Thread Matt Newell

> There are a number of strategies for dealing with this...
>
> 1. Manual inspection of the Qt source code and applying /ReleaseGIL/ where
> needed.
>
> 2. Automatically release the GIL whenever any Qt call is made. This was how
> SIP v3 worked (because it supported earlier versions of Python that didn't
> support PEP 311) and is still available in SIP v4 using the undocumented -g
> flag.
>
> 3. Automatically release the GIL whenever any Qt call is made from a
> QObject derived class. The assumption is that this will cover the vast
> majority of cases. Any other cases would have to be identified through bug
> reports.
>
> 1. is out of the question - unless somebody can recommend a good C++ source
> code analyzer.
>
> I tend towards 3.
>
> Comments?
>
Is there a significant performance cost to releasing the GIL?  If not it seems 
that 3 is a fine solution.  If there is a performance cost then maybe add an 
override /HoldGIL/ annotation or something for certain methods if people need 
the extra performance and the method has been shown to be safe.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-23 Thread Matt Newell
On Friday 23 February 2007 14:34, Matt Newell wrote:
> On Friday 23 February 2007 12:52, Matt Newell wrote:
> > On Friday 23 February 2007 12:38, Michael Guntsche wrote:
> > > On Feb 23, 2007, at 20:43, Matt Newell wrote:
> >
> > ...
> >
> > > Hello Matt,
> > >
> > > Can you try and change the connect to a QueuedConnection? It looks
> > > like it is using a "DirectConnection" now.
> > > I was sure I tried that before, but back then I was using events and
> > > not signals.
> >
> > It's already (correctly) using a queued connection to send the signal.
> > I've already tracked it down further and eliminated one of the deadlock
> > code paths by putting a /ReleaseGIL/ annotation on QLabel::setText. 
> > There is another deadlock though happening in the connect call which i'm
> > tracking down now.
> >
> > > I tried it on my computer, but although the "connect" returns True I
> > > do not get the emitted signal in my main thread.
> > > I do not understand why.
> >
> > Hmm, i'm not sure why that would happen.
>
> So here's the deal.  In order to avoid deadlocks we must avoid running any
> Qt code that will require a lock while the GIL is locked.  This is because
> we can't avoid the opposite, which is acquiring the GIL while Qt is holding
> a lock( For example Qt holds a lock while copying signal data for queued
> connections, and we have to run python code for that. )  To avoid a
> deadlock we must avoid one or the other.
>
> This means that any Qt calls that do a connect, or create/destroy any
> qobjects must first release the GIL.  There may be other code paths in Qt
> that require the same care.
>
> Try testing with this patch, it eliminates all deadlocks for me.
>
I still get deadlocks when destroying the threads unless I add /ReleaseGIL/ to 
the QThread dtor. 

I think that right now there are many potential deadlocks in PyQt.  All 
QObject and derived classes need their ctors and dtors marked /ReleaseGIL/.  
All connect/disconnect functions, any functions that indirectly delete or 
create qobjects, etc.  Essentially the entire api needs to be reviewed.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-23 Thread Matt Newell
On Friday 23 February 2007 12:52, Matt Newell wrote:
> On Friday 23 February 2007 12:38, Michael Guntsche wrote:
> > On Feb 23, 2007, at 20:43, Matt Newell wrote:
>
> ...
>
> > Hello Matt,
> >
> > Can you try and change the connect to a QueuedConnection? It looks
> > like it is using a "DirectConnection" now.
> > I was sure I tried that before, but back then I was using events and
> > not signals.
>
> It's already (correctly) using a queued connection to send the signal.
> I've already tracked it down further and eliminated one of the deadlock
> code paths by putting a /ReleaseGIL/ annotation on QLabel::setText.  There
> is another deadlock though happening in the connect call which i'm tracking
> down now.
>
> > I tried it on my computer, but although the "connect" returns True I
> > do not get the emitted signal in my main thread.
> > I do not understand why.
>
> Hmm, i'm not sure why that would happen.
>


So here's the deal.  In order to avoid deadlocks we must avoid running any Qt 
code that will require a lock while the GIL is locked.  This is because we 
can't avoid the opposite, which is acquiring the GIL while Qt is holding a 
lock( For example Qt holds a lock while copying signal data for queued 
connections, and we have to run python code for that. )  To avoid a deadlock 
we must avoid one or the other.

This means that any Qt calls that do a connect, or create/destroy any qobjects 
must first release the GIL.  There may be other code paths in Qt that require 
the same care.

Try testing with this patch, it eliminates all deadlocks for me.

Index: sip/QtGui/qlabel.sip
===
--- sip/QtGui/qlabel.sip(revision 4129)
+++ sip/QtGui/qlabel.sip(working copy)
@@ -84,7 +84,7 @@
 void setNum(int);
 void setPicture(const QPicture &);
 void setPixmap(const QPixmap &);
-void setText(const QString &);
+void setText(const QString &) /ReleaseGIL/;

 signals:
 %If (Qt_4_2_0 -)
Index: sip/QtCore/qobject.sip
===
--- sip/QtCore/qobject.sip  (revision 4129)
+++ sip/QtCore/qobject.sip  (working copy)
@@ -838,9 +838,11 @@
 mutex.unlock();

 // Detect when the transmitter is destroyed.
-if (tx)
+if (tx) {
+Py_BEGIN_ALLOW_THREADS
 connect(reinterpret_cast(tx), SIGNAL(destroyed(QObject 
*)), SLOT(deleteLater()));
-
+Py_END_ALLOW_THREADS
+}
 qtx = tx;
 }


Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-23 Thread Matt Newell
On Friday 23 February 2007 12:38, Michael Guntsche wrote:
> On Feb 23, 2007, at 20:43, Matt Newell wrote:
...
> Hello Matt,
>
> Can you try and change the connect to a QueuedConnection? It looks
> like it is using a "DirectConnection" now.
> I was sure I tried that before, but back then I was using events and
> not signals.

It's already (correctly) using a queued connection to send the signal.
I've already tracked it down further and eliminated one of the deadlock code 
paths by putting a /ReleaseGIL/ annotation on QLabel::setText.  There is 
another deadlock though happening in the connect call which i'm tracking down 
now.

> I tried it on my computer, but although the "connect" returns True I
> do not get the emitted signal in my main thread.
> I do not understand why.
>
Hmm, i'm not sure why that would happen.

Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-23 Thread Matt Newell

> I can reproduce this problem with the latest snapshot.  It seems that the
> main thread is waiting on a semaphore(Qt) for the worker threads while
> holding the python GIL.  The worker threads all get stuck waiting for the
> GIL.
>
> I'm going to compile a debug build and see if i can't figure this out
> further, here is the traces I have now with a release build.
>
> Matt
>

Here's the backtrace for each thread with debug pyqt.  I haven't studied it 
yet.

Matt
[EMAIL PROTECTED]:~/test2$ gdb python
GNU gdb 6.5-debian
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i486-linux-gnu"...(no debugging symbols found)
Using host libthread_db library "/lib/tls/libthread_db.so.1".

(gdb) run sample.pyw
Starting program: /usr/bin/python sample.pyw
Failed to read a valid object file image from memory.
(no debugging symbols found)
[Thread debugging using libthread_db enabled]
[New Thread -1209988448 (LWP 21998)]
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
[New Thread -1235154000 (LWP 22001)]
[New Thread -1243542608 (LWP 22002)]
[New Thread -1252271184 (LWP 22015)]
[New Thread -1260659792 (LWP 22016)]
[New Thread -1269048400 (LWP 22017)]
[New Thread -1277437008 (LWP 22018)]
[New Thread -1285825616 (LWP 22019)]
[New Thread -1296041040 (LWP 22020)]
[New Thread -1304429648 (LWP 22021)]
[New Thread -1312818256 (LWP 22022)]
[New Thread -1321206864 (LWP 22023)]

Program received signal SIGINT, Interrupt.
[Switching to Thread -1209988448 (LWP 21998)]
0xb7f78c01 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/tls/libpthread.so.0
(gdb) bt
#0  0xb7f78c01 in pthread_cond_wait@@GLIBC_2.3.2 () from 
/lib/tls/libpthread.so.0
#1  0xb7a5aca1 in QWaitCondition::wait (this=0x8250898, mutex=0x8250890, 
time=4294967295) at thread/qwaitcondition_unix.cpp:254
#2  0xb7a5706b in QReadWriteLock::lockForWrite (this=0x8253260) at 
thread/qreadwritelock.cpp:174
#3  0xb7b10fdf in ~QObject (this=0x8371e10) at 
../../include/QtCore/../../src/corelib/thread/qreadwritelock.h:122
#4  0xb6ba8c8d in ~QTextDocument (this=0x8371e10) at text/qtextdocument.cpp:302
#5  0xb6cf5673 in QLabelPrivate::clearContents (this=0x837d970) at 
widgets/qlabel.cpp:1167
#6  0xb6cf5aee in QLabel::setText (this=0x837d660, [EMAIL PROTECTED]) at 
widgets/qlabel.cpp:314
#7  0xb74b38a3 in meth_QLabel_setText (sipSelf=0xb676ed2c, sipArgs=0xb67ab14c) 
at sipQtGuiQLabel.cpp:2946
#8  0x080b9485 in PyEval_EvalFrame ()
#9  0x080ba745 in PyEval_EvalCodeEx ()
#10 0x08100b59 in PyClassMethod_New ()
#11 0x080589d7 in PyObject_Call ()
#12 0x0805e28e in PyClass_IsSubclass ()
#13 0x080589d7 in PyObject_Call ()
#14 0x080b3d2d in PyEval_CallObjectWithKeywords ()
#15 0xb7f9dee5 in initsip () from /usr/lib/python2.4/site-packages/sip.so
#16 0xb7c354e9 in PyQtProxy::invokeSlot ([EMAIL PROTECTED], qargs=0xbfb3859c) 
at sip/QtCore/qobject.sip:1102
#17 0xb7c35e63 in PyQtProxy::unislot (this=0x8387070, qargs=0xbfb3859c) at 
sip/QtCore/qobject.sip:971
#18 0xb7c35f6f in PyQtProxy::qt_metacall (this=0x8387070, 
_c=QMetaObject::InvokeMetaMethod, _id=1, _a=0xbfb3859c) at 
sip/QtCore/qobject.sip:925
#19 0xb7b105b5 in QMetaObject::activate (sender=0x83cfca8, 
from_signal_index=29, to_signal_index=30, argv=) at 
kernel/qobject.cpp:2940
#20 0xb7b10843 in QMetaObject::activate (sender=0x83cfca8, m=0xb6fe3104, 
from_local_signal_index=2, to_local_signal_index=3, argv=0xbfb3859c) at 
kernel/qobject.cpp:2992
#21 0xb6e83ea3 in QAbstractButton::clicked (this=0x83cfca8, _t1=false) at 
.moc/release-shared/moc_qabstractbutton.cpp:178
#22 0xb6cb156c in QAbstractButtonPrivate::emitClicked (this=0x83970b8) at 
widgets/qabstractbutton.cpp:517
#23 0xb6cb2d67 in QAbstractButtonPrivate::click (this=0x83970b8) at 
widgets/qabstractbutton.cpp:510
#24 0xb6cb2f70 in QAbstractButton::mouseReleaseEvent (this=0x83cfca8, 
e=0xbfb38c94) at widgets/qabstractbutton.cpp:1076
#25 0xb73f93fd in sipQPushButton::mouseReleaseEvent (this=0x83cfca8, 
a0=0xbfb38c94) at sipQtGuiQPushButton.cpp:330
#26 0xb6a703b3 in QWidget::event (this=0x83cfca8, event=0xbfb38c94) at 
kernel/qwidget.cpp:5698
#27 0xb6cb1f73 in QAbstractButton::event (this=0x83cfca8, e=0xbfb38c94) at 
widgets/qabstractbutton.cpp:1038
#28 0xb6d26444 in QPushButton::event (this=0x83cfca8, e=0xbfb38c94) at 
widgets/qpushbutton.cpp:582
#29 0xb73f43b6 in sipQPushButton::event (this=0x83cfca8, a0=0xbfb38c94) at 
sipQtGuiQPushButton.cpp:155
#30 0xb6a2f09c in QApplicationPrivate::notify_helper (this=0x82716d0, 
receiver=0x83cfca8, e=0xbfb38c94) at kernel/qapplication.cpp:3434
#31 0xb6a315bd in QApplication::notify (this=0x8272d10, receiver=0x83cfca8, 
e=0xbfb38c94) at kernel/qapplication.cp

Re: [PyKDE] Re: Threading problem with PyQt4 and Macosx

2007-02-23 Thread Matt Newell
On Friday 23 February 2007 09:15, Phil Thompson wrote:
> On Friday 23 February 2007 5:00 pm, Michael Guntsche wrote:
> > On Feb 23, 2007, at 17:09, Phil Thompson wrote:
> > > The Python 2.5 binary from python.org. Qt, SIP and PyQt all built
> > > without any
> > > flags to their respecting configure scripts.
> >
> > Ok, I officially give up now, no more ideas.
> > Is there any way I can debug this further?
>
> Just the usual. It's seems to be a deadlock as it only seems to be a
> problem if you have 2 cores.
>
> Phil
>

I can reproduce this problem with the latest snapshot.  It seems that the main 
thread is waiting on a semaphore(Qt) for the worker threads while holding the 
python GIL.  The worker threads all get stuck waiting for the GIL.

I'm going to compile a debug build and see if i can't figure this out further, 
here is the traces I have now with a release build.

Matt

- Main Thread BT ---

(gdb) bt
#0  0xb7f74c01 in pthread_cond_wait@@GLIBC_2.3.2 () 
from /lib/tls/libpthread.so.0
#1  0xb7af7ca1 in QWaitCondition::wait (this=0x834fd18, mutex=0x834fd10, 
time=4294967295) at thread/qwaitcondition_unix.cpp:254
#2  0xb7af406b in QReadWriteLock::lockForWrite (this=0x834e878) at 
thread/qreadwritelock.cpp:174
#3  0xb7badfdf in ~QObject (this=0x837aef0) 
at ../../include/QtCore/../../src/corelib/thread/qreadwritelock.h:122
#4  0xb6e7fc8d in ~QTextDocument (this=0x837aef0) at 
text/qtextdocument.cpp:302
#5  0xb6fcc673 in QLabelPrivate::clearContents (this=0x837b210) at 
widgets/qlabel.cpp:1167
#6  0xb6fccaee in QLabel::setText (this=0x837af00, [EMAIL PROTECTED]) at 
widgets/qlabel.cpp:314
#7  0xb75ae3fe in initQtGui () 
from /usr/lib/python2.4/site-packages/PyQt4/QtGui.so
#8  0x080b9485 in PyEval_EvalFrame ()
#9  0x080ba745 in PyEval_EvalCodeEx ()
#10 0x08100b59 in PyClassMethod_New ()
#11 0x080589d7 in PyObject_Call ()
#12 0x0805e28e in PyClass_IsSubclass ()
#13 0x080589d7 in PyObject_Call ()
#14 0x080b3d2d in PyEval_CallObjectWithKeywords ()
#15 0xb7f99ee5 in initsip () from /usr/lib/python2.4/site-packages/sip.so
#16 0xb7c75089 in initQtCore () 
from /usr/lib/python2.4/site-packages/PyQt4/QtCore.so
#17 0xb7c75992 in initQtCore () 
from /usr/lib/python2.4/site-packages/PyQt4/QtCore.so
#18 0xb7c75abc in initQtCore () 
from /usr/lib/python2.4/site-packages/PyQt4/QtCore.so
#19 0xb7bad5b5 in QMetaObject::activate (sender=0x83cd338, 
from_signal_index=29, to_signal_index=30, argv=) at 
kernel/qobject.cpp:2940
#20 0xb7bad843 in QMetaObject::activate (sender=0x83cd338, m=0xb72ba104, 
from_local_signal_index=2, to_local_signal_index=3, argv=0xbfa9ecfc) at 
kernel/qobject.cpp:2992
#21 0xb715aea3 in QAbstractButton::clicked (this=0x83cd338, _t1=false) 
at .moc/release-shared/moc_qabstractbutton.cpp:178
#22 0xb6f8856c in QAbstractButtonPrivate::emitClicked (this=0x8394758) at 
widgets/qabstractbutton.cpp:517
#23 0xb6f89d67 in QAbstractButtonPrivate::click (this=0x8394758) at 
widgets/qabstractbutton.cpp:510
#24 0xb6f89f70 in QAbstractButton::mouseReleaseEvent (this=0x83cd338, 
e=0xbfa9f3f4) at widgets/qabstractbutton.cpp:1076
#25 0xb7510d0c in initQtGui () 
from /usr/lib/python2.4/site-packages/PyQt4/QtGui.so
#26 0xb6d473b3 in QWidget::event (this=0x83cd338, event=0xbfa9f3f4) at 
kernel/qwidget.cpp:5698
#27 0xb6f88f73 in QAbstractButton::event (this=0x83cd338, e=0xbfa9f3f4) at 
widgets/qabstractbutton.cpp:1038
#28 0xb6ffd444 in QPushButton::event (this=0x83cd338, e=0xbfa9f3f4) at 
widgets/qpushbutton.cpp:582
#29 0xb750c480 in initQtGui () 
from /usr/lib/python2.4/site-packages/PyQt4/QtGui.so
#30 0xb6d0609c in QApplicationPrivate::notify_helper (this=0x8249e30, 
receiver=0x83cd338, e=0xbfa9f3f4) at kernel/qapplication.cpp:3434
#31 0xb6d085bd in QApplication::notify (this=0x826bf08, receiver=0x83cd338, 
e=0xbfa9f3f4) at kernel/qapplication.cpp:3133
#32 0xb76ebf03 in initQtGui () 
from /usr/lib/python2.4/site-packages/PyQt4/QtGui.so
#33 0xb6d5c8cb in QETWidget::translateMouseEvent (this=0x83cd338, 
event=0xbfa9f6a8) 
at ../../include/QtCore/../../src/corelib/kernel/qcoreapplication.h:186
#34 0xb6d5beef in QApplication::x11ProcessEvent (this=0x826bf08, 
event=0xbfa9f6a8) at kernel/qapplication_x11.cpp:2764
#35 0xb6d7eb43 in QEventDispatcherX11::processEvents (this=0x827aa28, 
[EMAIL PROTECTED]) at kernel/qeventdispatcher_x11.cpp:112
#36 0xb7b9a751 in QEventLoop::processEvents (this=0xbfa9f800, 
[EMAIL PROTECTED]) at kernel/qeventloop.cpp:126
#37 0xb7b9a85a in QEventLoop::exec (this=0xbfa9f800, [EMAIL PROTECTED]) at 
kernel/qeventloop.cpp:172
#38 0xb7b9c9c6 in QCoreApplication::exec () at kernel/qcoreapplication.cpp:727
#39 0xb6d05b37 in QApplication::exec () at kernel/qapplication.cpp:2927
#40 0xb76ecc1d in initQtGui () 
from /usr/lib/python2.4/site-packages/PyQt4/QtGui.so
#41 0x080b9485 in PyEval_EvalFrame ()
#42 0x080ba745 in PyEval_EvalCodeEx ()
#43 0x080ba7a9 in PyEval_EvalCode ()
#44 0x080dd157 in PyRun_FileExFlags ()
#45 0x080dd354 in PyRun_SimpleFileExFlags ()
#46 0x08055ba8 in Py_Main 

Re: [PyKDE] SIP automatically casting up to a QWidget

2007-02-22 Thread Matt Newell
On Thursday 22 February 2007 06:32, Phil Thompson wrote:
> On Thursday 22 February 2007 1:53 pm, Paul Giannaros wrote:
> > I have a class A that i'm wrapping with SIP. The class inherits from a
> > bunch of other classes. One of the classes it inherits from also in turn
> > inherits from QWidget. When I import the created module, whenever I call
> > a method that is meant to return an instance of class A I get a QWidget
> > instead. I can use sip.cast to get the QWidget back to an A instance, but
> > that's not a very friendly solution.
> > Can someone suggest why this is happening, or how to fix it?
>
> You need to implement %ConvertToSubClassCode that handles A (and any other
> QObject derived classes in your module).
>

While I understand the use of %ConvertToSubClassCode, it seems to me that it 
should not be required for this case.  If the class hierarchy is

QWidget -> A

and the function signature already shows that the function returns class A, 
why should convertSubClass ever convert it to a QWidget?

I changed my sip a while ago for this case, since I have many Dialogs and 
widgets wrapped with sip that I don't really need automatic converters for, 
but don't want them downgraded to a QWidget when they are constructed.

Here's the code I have inside the while loop in convertToSubClass.  

/*
* The base type is the "root" class that may have a number of
* convertors each handling a "branch" of the derived tree of
* classes.  The "root" normally implements the base function that
* provides the RTTI used by the convertors and is re-implemented
* by derived classes.  We therefore see if the target type is a
* sub-class of the root, ie. see if the convertor might be able to
* convert the target type to something more specific.
*/
if (PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)scc->scc_basetype))
{
sipWrapperType *subtype;
subtype = (*scc->scc_convertor)(cppPtr);
/*
* Because a base module with convertToSubClass code may know 
how to convert
* A -> B -> C
* a derived module may have a class D that inherits from C, 
* so the base module may believe it is converting to a more 
specific type
* by converting to C, when in fact D is already the most 
specific type.
*/
if (subtype && !PyType_IsSubtype((PyTypeObject*)type, 
(PyTypeObject*)subtype) )
return subtype;
}


Matt

___
PyKDE mailing listPyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde


  1   2   >