头文件:
- #ifndef WIDGET_H
- #define WIDGET_H
-
- #include
- #include
- #include
- #include
- #include
- #include
//文件对话框 - #include
-
- class Widget : public QWidget
- {
- Q_OBJECT
-
- public:
- Widget(QWidget *parent = 0);
- ~Widget();
- private slots:
- void down_pic();
- void up_pic();
- void open_pic();
-
- private:
- QPushButton *pb_open,*pb_prior,*pb_next;
- QLabel *l;
- QStringList filenames;
- int pos;
- };
-
- #endif // WIDGET_H
cpp文件;
- #include "widget.h"
-
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- {
- l = new QLabel("showpic");
- l->setFixedSize(640,480);
- l->setScaledContents(true); //自适应
- l->setAlignment(Qt::AlignCenter);//居中对齐
-
- pb_open = new QPushButton;//("open");//加了图片就不用标题了
- pb_prior = new QPushButton;//("Prior");
- pb_next = new QPushButton;//("Next");
- pb_open->setFixedSize(50,50);
- pb_next->setFixedSize(50,50); //设置按钮大小
- pb_prior->setFixedSize(50,50);
-
- pb_open->setIcon(QIcon(":/pic/回调函数.png"));//给按钮加上图标
- pb_open->setIconSize(pb_open->size());//设置图标大小
- pb_open->setFlat(true); //设置按钮的透明
-
- pb_next->setIcon(QIcon(":/pic/封包拆包.png"));
- pb_next->setIconSize(pb_next->size());//设置图标大小
- pb_next->setFlat(true); //设置按钮的透明
-
- pb_prior->setIcon(QIcon(":/pic/软件.png"));
- pb_prior->setIconSize(pb_prior->size());//设置图标大小
- pb_prior->setFlat(true); //设置按钮的透明
-
- pb_prior->setEnabled(false);//先使左右键失能,打开图片后再使能
- pb_next->setEnabled(false);
-
- QHBoxLayout *hbox = new QHBoxLayout;
- hbox->addStretch();//设置弹簧
- hbox->addWidget(pb_prior);
- hbox->addWidget(pb_open);
- hbox->addWidget(pb_next);
- hbox->addStretch(); //设置弹簧,使按键靠中间,较好看
-
- QVBoxLayout *vbox = new QVBoxLayout;
- vbox->addWidget(l);
- vbox->addLayout(hbox);
-
- setLayout(vbox);
-
- connect(pb_prior,SIGNAL(clicked(bool)),this,SLOT(up_pic()));
- connect(pb_open,SIGNAL(clicked(bool)),this,SLOT(open_pic()));
- connect(pb_next,SIGNAL(clicked(bool)),this,SLOT(down_pic()));
-
-
- }
-
- Widget::~Widget()
- {
-
- }
-
- void Widget::down_pic()
- {
- if(pos==filenames.length()-1)//循环显示
- pos=0;
- else
- pos++;
- l->setPixmap(QPixmap(filenames.at(pos)));
- }
-
- void Widget::up_pic()
- {
- if(pos==0) //循环显示
- pos=filenames.length()-1;
- else
- pos--;
- l->setPixmap(QPixmap(filenames.at(pos)));
- }
-
- void Widget::open_pic()
- {
- QStringList names = QFileDialog::getOpenFileNames(this,"打开图片",".","Images(*.png *.jpg *.bmp)");
- if(names.isEmpty())//没打开图片
- return;
- filenames = names;//第二次没打开,还可以查看上一次打开的图片
- pos=0;
- l->setPixmap(QPixmap(filenames.at(pos)));
- pb_prior->setEnabled(true);
- pb_next->setEnabled(true);
- }