[Kde-bindings] [Qyoto] Casting QObjects

Mach metator.pt at gmail.com
Thu May 24 19:54:55 UTC 2012


Hi all,

I've managed to compile qyoto on windows and now i'm doing some test 
applications to try it out. I'm having trouble trying to downcast 
QObjects. Traditional casting in C# does not work, but i was expecting 
that. So i started to look for something that could perform a cast and 
found the method Cast(QObject) in QMetaObject but it's not working 
always. Below is an example application that tries to cast all the 
children of the main window to widgets. Notice that i previously check 
if the object is a widget type:

using System;
using Qyoto;

namespace QtTest {
     class Program {
         [STAThread]
         static void Main(string[] args) {
             QApplication app = new QApplication(args);
             QMainWindow win = new QMainWindow();
             QPushButton btn = new QPushButton(win);
             win.WindowTitle = "Demo Application";
             win.Show();
             foreach (QObject child in win.Children()) {
                 if (child.IsWidgetType()) {
                     try {
                         QWidget widget = (QWidget) 
child.MetaObject().Cast(child);
                         Console.WriteLine("Cast succeeded. It's now a " 
+ widget.GetType().Name);
                     } catch (InvalidCastException e) {
                         Console.WriteLine(child.ObjectName + " of type 
" + child.MetaObject().ClassName() +
                                           " cannot be cast to QWidget");
                     }
                 }
             }
             QApplication.Exec();
         }
     }
}

The output on the console is:

qt_rubberband of type QRubberBand cannot be cast to QWidget
Cast succeeded. It's now a QPushButton

I suspect this has something to do with the fact that qt_rubberband was 
created on the unmanaged side, whereas QPushButton was created by the 
managed side. I also tried calling 
QWidget.StaticMetaObject.Cast(QObject) but it's always returning null.

Can someone help me out solving this problem?

Thanks in advance. Regards




More information about the Kde-bindings mailing list