QT:图片按钮(改进版)

之前我写过一个可以直接显示图片的Button: http://blog.csdn.net/aaa20090987/article/details/6789380

当时为了方便,直接用QFrame作为它的基类,结果(布局,使用等)十分不方便,大哭

还是老老实实地用 QAbstractButton 作为基类,再用paintEvent来画图吧


//tqt.h
#ifndef TQT_H_
#define TQT_H_

#include <QtGui>
#include <QtCore>

class PictureButton : public QAbstractButton
{
	Q_OBJECT
private:
	QPixmap pixmap;
protected:
	virtual void paintEvent(QPaintEvent *event);
	virtual QSize sizeHint() const;
public:
	PictureButton(const QString &path, QWidget *parent=0);
	PictureButton(QWidget *parent = 0);
	~PictureButton();
	void setPixmap(const QString &path);
};


class Widget : public QWidget
{
	Q_OBJECT
private:
	QLabel *label;
	PictureButton *prevButton;
	PictureButton *nextButton;
	int num;

public:
	Widget(QWidget *parent = 0);
	~Widget();

	public slots:
		void ClickedPrevButton();
		void ClickedNextButton();
};

#endif


//tqt.cpp
#include "tqt.h"

PictureButton::PictureButton(const QString &path, QWidget *parent/* =0 */)
: QAbstractButton(parent)
{
	setPixmap(path);
	setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}

PictureButton::PictureButton(QWidget *parent /* = 0 */)
: QAbstractButton(parent)
{
	setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}


PictureButton::~PictureButton()
{

}

void PictureButton::paintEvent(QPaintEvent *event)
{
	QPainter painter(this);
	painter.drawPixmap(0, 0, width(), height(), pixmap);
}

QSize PictureButton::sizeHint() const 
{
	return pixmap.size();
}

void PictureButton::setPixmap(const QString &path)
{
	pixmap.load(path);
	update();
}

Widget::Widget(QWidget *parent) 
: QWidget(parent)
{
	num = 0;
	label = new QLabel("0", this);
	//prev.jpg和next.jpg是当前文件夹中的两张JPG图片
	prevButton = new PictureButton("prev.jpg", this);
	nextButton = new PictureButton("next.jpg", this);

	QHBoxLayout *subLayout = new QHBoxLayout;
	QVBoxLayout *layout = new QVBoxLayout;
	subLayout->addWidget(prevButton);
	subLayout->addWidget(nextButton);
	layout->addWidget(label);
	layout->addLayout(subLayout);
	setLayout(layout);

	setWindowTitle("Widget");
	resize(200, 200);
	connect(prevButton, SIGNAL(clicked()), this, SLOT(ClickedPrevButton()));
	connect(nextButton, SIGNAL(clicked()), this, SLOT(ClickedNextButton()));
}

Widget::~Widget()
{

}

void Widget::ClickedPrevButton()
{
	num--;
	label->setText(QString::number(num));
}

void Widget::ClickedNextButton()
{
	num++;
	label->setText(QString::number(num));
}


//main.cpp
#include "tqt3.h"

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	Widget w;
	w.show();
	return a.exec();
}

注意:这个程序是用来研究的(或者说是玩的),如果要在按钮上加图片的话,直接用QToolButton就可以了

你可能感兴趣的:(layout,Class,qt,Path,button,Signal)