☆Smoozer☆

::Easy Life.
如何处理QToolBox上QToolBoxButton的click事件?

Problem:
QToolBox,QTabWidget,QTabBar是通过currentChanged(int)这个signal来得到当前的currentIndex改变的。
Suppose在QToolBox上有3个QToolBoxButton, 每个QToolBoxButton下又有2个item,当我选中第二个QToolBoxButton下的任意一个item的时候,这时候QToolBox的currentIndex是1. 这时候再去点击current QToolBoxButton的时候,是没有currentChanged(int) signal发出的。如果我就是想处理点击同一个QToolBoxButton的情况呢?


可能你也想到了,得到QToolBoxButton的指针不就ok了吗?Unfortunately,类似于QTabBar上的Tab这个structure,QToolBox里的QToolBoxButton也是private,我们无法通过“正常途径"得到。

既然此路不通,就另辟蹊径,QObject的函数findChildren()可以出场了。。。

QList<T> QObject::findChildren ( const QString & name = QString() ) const

Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. Omitting the name argument causes all object names to be matched. The search is performed recursively.

The following example shows how to find a list of child QWidgets of the specified parentWidget named widgetname:
         QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname");
This example returns all QPushButtons that are children of parentWidget:
         QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();


QToolBoxButton的base class是QTbstractButton,这些QToolBoxButton的objectName都是”qt_toolbox_QToolBoxButton“,因此,我们的代码可以这样写:
QList<QAbstractButton *> btnlist = findChildren<QAbstractButton*>(tr("qt_toolbox_QToolBoxButton"));

接下来的处理方式就有很多了,installEventFilter或者直接connect clicked() signal。。。
QAbstractButton* btn = NULL;
qint32 counter = btnlist.count();
for (qint32 i = 0; i < counter; i++)
{
    btn = btnlist.at(i);
    btn->installEventFilter(this); // method 1.
    // connect(btn, SIGNAL(clicked()), this, SLOT(toolboxbtnClicked())); // method 2.
}

举一反三,QT其他的很多widget的私有widget也可以通过这种方式获得。This is tricky. Yet, QT supplies us one method at least.

 

posted on 2009-06-19 20:54  smoozer  阅读(3050)  评论(0编辑  收藏  举报