Qt:如何绘制虚拟线编辑控件

时间:2012-03-27 20:57:29

标签: qt

我有一个QPainter和一个矩形。

我想绘制一个空的QLineEdit控件。只是为了绘制它,而不是实时控制。我怎么做?我试过QStyle :: drawPrimitive无济于事。什么都没画。

 QStyleOption option1;
 option1.init(contactsView); // contactView is the parent QListView
 option1.rect = option.rect; // option.rect is the rectangle to be drawn on.
 contactsView->style()->drawPrimitive(QStyle::PE_FrameLineEdit, &option1, painter, contactsView);

当然,我希望绘制的假人在Windows和OSX中看起来是原生的。

1 个答案:

答案 0 :(得分:1)

您的代码非常接近,但您必须从假QLineEdit初始化样式。以下内容基于QLineEdit::paintEventQLineEdit::initStyleOption

#include <QtGui>

class FakeLineEditWidget : public QWidget {
public:
  explicit FakeLineEditWidget(QWidget *parent = NULL) : QWidget(parent) {}
protected:
  void paintEvent(QPaintEvent *) {
    QPainter painter(this);

    QLineEdit dummy;

    QStyleOptionFrameV2 panel;
    panel.initFrom(&dummy);
    panel.rect = QRect(10, 10, 100, 30);  // QFontMetric could provide height.
    panel.lineWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth,
                                           &panel,
                                           &dummy);
    panel.midLineWidth = 0;
    panel.state |= QStyle::State_Sunken;
    panel.features = QStyleOptionFrameV2::None;

    style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panel, &painter, this);
  }
};

int main(int argc, char **argv) {
  QApplication app(argc, argv);

  FakeLineEditWidget w;
  w.setFixedSize(300, 100);
  w.show();

  return app.exec();
}