2009-09-17 62 views
3

我想知道是否可以在PyQt和Boost.Python之間共享小部件。在PyQT和Boost.Python之間共享小部件

我將嵌入一個Python解釋器到我的使用Qt的應用程序中。我希望我的應用程序的用戶能夠將自己的UI小部件嵌入到用C++編程的UI小部件中,並通過Boost.Python公開。

這是可能的嗎?怎麼會這樣做呢?

回答

2

我試着爲此編寫一些代理,但我沒有完全成功。這是一個試圖解決這個問題的開始,但是dir()不起作用。調用函數直接起作用。

這個想法是創建一個包裝在SIP中的附加python對象,並且如果原始boost.python對象沒有任何匹配屬性,則將任何調用/屬性轉發給該對象。

儘管如此,我還不夠Python的專家。 :(

(我把這個變成一個wiki,所以脂肪酶可以編輯和更新在這裏,因爲這個代碼只是半吊子樣板)

C++:

#include "stdafx.h"  
#include <QtCore/QTimer> 

class MyWidget : public QTimer 
{ 
public: 
    MyWidget() {} 
    void foo() { std::cout << "yar\n"; } 
    unsigned long myself() { return reinterpret_cast<unsigned long>(this); } 
}; 

#ifdef _DEBUG 
BOOST_PYTHON_MODULE(PyQtBoostPythonD) 
#else 
BOOST_PYTHON_MODULE(PyQtBoostPython) 
#endif 
{ 
    using namespace boost::python; 

    class_<MyWidget, bases<>, MyWidget*, boost::noncopyable>("MyWidget"). 
     def("foo", &MyWidget::foo). 
     def("myself", &MyWidget::myself); 
} 

的Python:

from PyQt4.Qt import * 
import sys 

import sip 
from PyQtBoostPythonD import * # the module compiled from cpp file above 

a = QApplication(sys.argv) 
w = QWidget() 
f = MyWidget() 

def _q_getattr(self, attr): 
    if type(self) == type(type(MyWidget)): 
    raise AttributeError 
    else: 
    print "get %s" % attr 
    value = getattr(sip.wrapinstance(self.myself(), QObject), attr) 
    print "get2 %s returned %s" % (attr, value) 
    return value 

MyWidget.__getattr__ = _q_getattr 

def _q_dir(self): 
    r = self.__dict__ 
    r.update(self.__class__.__dict__) 
    wrap = sip.wrapinstance(self.myself(), QObject) 
    r.update(wrap.__dict__) 
    r.update(wrap.__class__.__dict__) 
    return r 

MyWidget.__dir__ = _q_dir 

f.start() 
f.foo() 
print dir(f) 
相關問題