该例程实现窗口部件Ticker,该窗口部件显示了一串文本标语,它会每30毫秒向左移动一个像素,效果为字幕滚动。以下为书中的实现代码:
ticker.h
#ifndef TICKER_H
#define TICKER_H
#include <QWidget>
namespace Ui
{
class Ticker;
}
class Ticker :public QWidget
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText)
public:
Ticker(QWidget *parent = 0);
// ~Ticker();
void setText(const QString &newText);
QString text() const {return myText;}
QSize sizeHint() const;
protected:
void paintEvent(QPaintEvent *event);
void timerEvent(QTimerEvent *event);
void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event);
private:
QString myText;
int offset;
int myTimerId;
};
#endif // TICKER_H
ticker.cpp
#include <QtGui>
#include "ticker.h"
Ticker::Ticker(QWidget *parent)
:QWidget(parent)
//,ui(new Ui::Ticker)
{
//ui->setupUi(this);
offset = 0;
myTimerId = 0;
}
void Ticker::setText(const QString &newText)
{
myText = newText;
// update();
// updateGeometry();
}
QSize Ticker::sizeHint() const
{
return fontMetrics().size(0,text());
}
void Ticker::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
int textWidth = fontMetrics().width(text());
if(textWidth < 1)
return;
int x = -offset;
while(x < width())
{
painter.drawText(x,0,textWidth,height(),Qt::AlignLeft | Qt::AlignVCenter,text());
x += textWidth;
}
}
void Ticker::showEvent(QShowEvent *event)
{
myTimerId = startTimer(30);
}
void Ticker::timerEvent(QTimerEvent *event)
{
if(event->timerId() == myTimerId)
{
++offset;
if(offset >= fontMetrics().width(text()))
offset = 0;
scroll(-1,0);
}
else
{
QWidget::timerEvent(event);
}
}
void Ticker::hideEvent(QHideEvent *event)
{
killTimer(myTimerId);
myTimerId = 0;
}
main.cpp
#include <QApplication>
#include "ticker.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
Ticker ticker;
ticker.setWindowTitle(QObject::tr("Ticker"));
ticker.setText("How long it lasted say ++ ");
ticker.show();
return app.exec();
}
我想问的是在main函数中,
为什么就显示不了构造的Ticker窗口部件,必须得加上ticker.setText函数才行呢?
Ticker ticker;
ticker.show()
Ticker ticker;这句不是已经构造对象了吗?
ticker.show();这句不是显示构造的窗口对象吗?
为什么就是不行呢?
------解决方案--------------------
这个空间本身是透明的,没有文本的时候实际上也是存在的,只是你看不到罢了,加上文本,你就看到了