Qt基础控件学习01 自定义QTreeWidget 图标显示在右边

之前项目需要这样一个控件作为切换窗口的。于是想到了QTreewidget.刚开始不知道怎么把图片放在右边,查了很多博客。发现有很多人有同样的问题,于是自己码了一下,发现挺简单的,废不多;看效果,上源码!
Qt基础控件学习01 自定义QTreeWidget 图标显示在右边_第1张图片
ui->treeWidget->setColumnCount(1); //设置列数
ui->treeWidget->setFocusPolicy(Qt::NoFocus);
ui->treeWidget->header()->hide();
ui->treeWidget->setLayoutDirection(Qt::RightToLeft);//设置右到左排列
ui->treeWidget->setRootIsDecorated(false); //隐藏根节点项前的图标(展开折叠图标)

QTreeWidgetItem *widgetItem1 = new QTreeWidgetItem(ui->treeWidget,QStringList(QString("父选项1   ")),0);
QTreeWidgetItem *widgetItem1_1 = new QTreeWidgetItem(widgetItem1,QStringList(QString("子选项1")),1); //子节点1
widgetItem1->addChild(widgetItem1_1); //添加子节点

widgetItem1->setIcon(0,QIcon(":/images/left1.png"));
widgetItem1->setTextAlignment(0,Qt::AlignRight);//必要,这个也要往右排列,因为前面设置了setLayoutDirection

QTreeWidgetItem *widgetItem2 = new QTreeWidgetItem(ui->treeWidget,QStringList(QString("父选项2   ")),2);
widgetItem2->setIcon(0,QIcon(":/images/left1.png"));
QTreeWidgetItem *widgetItem2_1 = new QTreeWidgetItem(widgetItem2,QStringList(QString("子选项1")),3); //子节点1
QTreeWidgetItem *widgetItem2_2 = new QTreeWidgetItem(widgetItem2,QStringList(QString("子选项2")),4); //子节点2
widgetItem2->addChild(widgetItem2_1); //添加子节点
widgetItem2->addChild(widgetItem2_2); //添加子节点
QTreeWidgetItem *widgetItem3 = new QTreeWidgetItem(ui->treeWidget,QStringList(QString("父选项3   ")),5);
connect(ui->treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(showSelectedWidget(QTreeWidgetItem*,int)));
widgetItem2->setTextAlignment(0,Qt::AlignRight);
widgetItem3->setTextAlignment(0,Qt::AlignRight);

widgetItem1_1->setTextAlignment(0,Qt::AlignHCenter);
widgetItem2_1->setTextAlignment(0,Qt::AlignHCenter);
widgetItem2_2->setTextAlignment(0,Qt::AlignHCenter);

//点击选项卡的槽
void MainWindow::showSelectedWidget(QTreeWidgetItem *item, int column)
{
int type = item->type();
qDebug()<<"type "<

switch (type) {
case 1:
{
    ui->stackedWidget->setCurrentIndex(0);
}
    break;
case 3:
{
    ui->stackedWidget->setCurrentIndex(1);
}
    break;
case 4:
{
    ui->stackedWidget->setCurrentIndex(2);
}
    break;
case 5:
{
    ui->stackedWidget->setCurrentIndex(3);
}
    break;
default:
    if(item->isExpanded())
    {
        item->setExpanded(false);
        item->setIcon(0,QIcon(":/images/left1.png"));
    }else
    {
        item->setExpanded(true);
        item->setIcon(0,QIcon(":/images/down1.png"));
    }
    break;
}

}

样式:(可以根据自己的样式修改,这里只是随便copy了一下别人写好的)
QTreeWidget::item:selected{
border:1px solid transparent;
font: 15px “ubuntu”;
color:#51637e;
}

QTreeWidget::branch {
background: white;
}

QTreeWidget::item:hover{background-color:rgb(0,255,0,50);
}
QTreeWidget::item:selected{background-color:rgb(255,0,0,100)}

你可能感兴趣的:(QT控件)