初学Qt之---设置组件样式和添加滚动条

       这个例子中增加了滚动条的实现,以及通过stylesheet对组件的样式进行控制。

      主要代码如下:

 

#include "MainFrame.h"
#include <iostream>
#include <QtGui/QIcon>

MainFrame::MainFrame()
{
  widget=NULL;
  setGeometry(0,0,500,300);
 
  this->setAutoFillBackground(true);
  QPalette palette;
  palette.setBrush(QPalette::Background, QBrush(QPixmap("/workspace/image/test1.jpg")));
  this->setPalette(palette);

  QPalette palette2;
  palette2.setBrush(QPalette::Background, QBrush(QPixmap("/workspace/image/test2.jpg")));

  QPushButton *button_add=new QPushButton("addButton",this);
  QPushButton *button_del=new QPushButton("delButton",this);
  button_add->setGeometry(20,20,200,50);
  button_add->setObjectName("button_add");
  button_add->setStyleSheet("QPushButton#button_add{color:red;background:url(/workspace/image/test2.jpg);font-size:20px};");

  button_del->setGeometry(240,20,200,50);
  button_del->setObjectName("button_del");
  button_del->setStyleSheet("QPushButton#button_del{color:red;background:url(/workspace/image/test2.jpg);font-size:20px};");
  
  connect(button_add,SIGNAL(clicked()),this,SLOT(addButton()));
  connect(button_del,SIGNAL(clicked()),this,SLOT(delButton()));
  scrollArea = new QScrollArea(this);
  scrollArea->setGeometry(20,100,460,180);
  
}

MainFrame::~MainFrame()
{
}

void MainFrame::addButton()
{
   std::cout<<"addButton clicked!"<<std::endl;
   if(widget!=NULL){
     widget->hide();
     widget=NULL;
   }
   widget=new QWidget();
   widget->setGeometry(0,0,460,400);
  
   QPushButton *button1=new QPushButton("AAAAAAAAAA",widget);
   button1->setObjectName("button_extra");
   QPushButton *button2=new QPushButton("BBBBBBBBBB",widget);
   button2->setObjectName("button_extra");
   QPushButton *button3=new QPushButton("CCCCCCCCCC",widget);
   button3->setObjectName("button_extra");
   QPushButton *button4=new QPushButton("DDDDDDDDDD",widget);
   button4->setObjectName("button_extra");
   QPushButton *button5=new QPushButton("EEEEEEEEEE",widget);
   button5->setObjectName("button_extra");
   widget->setObjectName("widget");

   button1->setGeometry(20,0,200,50);
   button2->setGeometry(20,100,200,50);
   button3->setGeometry(20,190,200,50);
   button4->setGeometry(20,250,200,50);
   button5->setGeometry(20,310,200,50);
   scrollArea->setWidget(widget);
   widget->setStyleSheet("QPushButton#button_extra{color:red;background:url(/workspace/image/test3.jpg);font-size:20px}QWidget#widget{color:red;background:url(/workspace/image/test1.jpg);font-size:20px}");   //注意这儿分别设置了button_extra和widget的样式
   widget->show();
}

void MainFrame::delButton()
{
   std::cout<<"delButton clicked!"<<std::endl;
   if(widget!=NULL){
     widget->hide();
     widget=NULL;
   }
}

运行结果截图:

(---------完--------)

你可能感兴趣的:(qt)