[QT]QT教程之实例分析[三] 实现QQ抽屉效果(QToolBox 和QToolButton)时间:2022-10-14 05:30:48重点知识已近在代码里注释...请仔细看代码本文原创转载请保留此链接 http://blog.csdn.net/siren0203 头文件 drawer.h #ifndef DRAWER_H#define DRAWER_H#include <QToolBox>class QToolButton;#include <QObject>//QToolBox提供一种列状的层叠窗体class Drawer:public QToolBox{ Q_OBJECTpublic: Drawer(QWidget *parent=0); QToolButton *toolButton1_1; QToolButton *toolButton1_2;private slots: void slotCls();};#endif // DRAWER_H 实现文件 main.cpp #include <QApplication>#include <QToolButton>#include <QToolBox>#include <QGroupBox>#include <QVBoxLayout>#include <QWidget>#include <QTextCodec>#include <QMessageBox>#include "drawer.h"//构造函数初始化布局控件Drawer::Drawer(QWidget *parent):QToolBox(parent){ //设置标题 setWindowTitle(tr("QQ")); //创建一个 QGroupBox 对象 QGroupBox *groupBox1=new QGroupBox(this); //创建按钮1 toolButton1_1=new QToolButton; toolButton1_1->setText(tr("siren")); toolButton1_1->setAutoRaise(TRUE); //鼠标离开时 按钮恢复到谈起状态 toolButton1_1->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); //文字显示在图标下面 //创建一个 QGroupBox 对象 QGroupBox *groupBox2=new QGroupBox(this); //创建按钮二 toolButton1_2=new QToolButton; toolButton1_2->setText(tr("http://blog.csdn.net/siren0203")); toolButton1_2->setAutoRaise(TRUE); toolButton1_2->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); //第一个抽屉 QVBoxLayout *layout1=new QVBoxLayout(groupBox1); layout1->setMargin(10); layout1->setAlignment(Qt::AlignHCenter); layout1->addWidget(toolButton1_1); //第二个抽屉 QVBoxLayout *layout2=new QVBoxLayout(groupBox2); layout2->setMargin(10); layout2->setAlignment(Qt::AlignHCenter); layout2->addWidget(toolButton1_2); //把抽屉插入到 QToolBox中 this->addItem((QWidget *)groupBox1,tr("userName")); this->addItem((QWidget *)groupBox2,tr("homePage")); connect(toolButton1_1,SIGNAL(clicked()),this,SLOT(slotCls()));}void Drawer::slotCls(){ QMessageBox *msg=new QMessageBox(this); msg->setText("user name is Riren"); msg->exec();}int main(int argc,char ** argv){ QApplication app(argc,argv); Drawer drawc; drawc.show(); return app.exec();} 效果如下