我正在嘗試創建一個自定義小部件。我的Widget呈現自己,除非它位於滾動區域內。下面的代碼工作。如果我在MainWindow構造函數中將if(0)更改爲if(1),它將不會呈現「Hello World」字符串。我假設我必須(重新)實施一些額外的方法,但到目前爲止,我還沒有能夠通過試驗和錯誤找到正確的方法。Qt:QScrollArea中的自定義小部件
// hellowidget.h
#ifndef HELLOWIDGET_H
#define HELLOWIDGET_H
#include <QtGui>
class HelloWidget : public QWidget
{
Q_OBJECT
public:
HelloWidget(QWidget *parent = 0);
void paintEvent(QPaintEvent *event);
};
#endif // HELLOWIDGET_H
// hellowidget.cpp
#include "hellowidget.h"
HelloWidget::HelloWidget(QWidget *parent)
: QWidget(parent)
{
}
void HelloWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawText(rect(), Qt::AlignCenter, "Hello World");
}
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private:
};
#endif // MAINWINDOW_H
// mainwindow.cpp
#include "mainwindow.h"
#include "hellowidget.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
HelloWidget *hello = new HelloWidget;
QWidget *central = hello;
if(0)
{
QScrollArea *scroll = new QScrollArea ;
scroll->setWidget(hello);
central = scroll;
}
setCentralWidget(central);
}
MainWindow::~MainWindow()
{
}
// main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
是否調用了paintEvent函數?我會在那裏放一個qDebug()語句,或者在調試器中斷開。如果沒有被調用,我會認爲這可能是一個大小問題。嘗試重新實現resizeEvent()並查看該小部件的設置大小。我敢打賭,它永遠不會比(0,0)大,這意味着沒有任何東西可以繪製。 – 2009-06-16 02:38:47