class CustomScrollArea : public QScrollArea{public: CustomScrollArea(QWidget *parent = nullptr);protected: void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void paintEvent(QPaintEvent *event) override;private: QPoint m_lastPos; // 上一次鼠标移动的位置 QPixmap m_pixmap; // 绘制的图片 int m_offset; // 图片偏移量};CustomScrollArea::CustomScrollArea(QWidget *parent) : QScrollArea(parent) , m_offset(0){ // 设置水平滚动条不可见 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 设置垂直滚动条不可见 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 设置背景色为白色 setStyleSheet("background-color:white;");}void CustomScrollArea::mousePressEvent(QMouseEvent *event){ if (event->button() == Qt::LeftButton) { m_lastPos = event->pos(); }}void CustomScrollArea::mouseMoveEvent(QMouseEvent *event){ if (event->buttons() & Qt::LeftButton) { int dx = event->pos().x() - m_lastPos.x(); m_offset += dx; m_lastPos = event->pos(); // 如果偏移量超过了图片的宽度,则拼接到最开始的地方 if (m_offset >= m_pixmap.width()) { m_offset -= m_pixmap.width(); } else if (m_offset < 0) { m_offset += m_pixmap.width(); } update(); }}void CustomScrollArea::paintEvent(QPaintEvent *event){ QPainter painter(viewport()); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::SmoothPixmapTransform); // 绘制背景 painter.fillRect(viewport()->rect(), Qt::white); // 绘制图片 painter.drawPixmap(m_offset, 0, m_pixmap); if (m_offset > 0) { painter.drawPixmap(m_offset - m_pixmap.width(), 0, m_pixmap); } if (m_offset + m_pixmap.width() < viewport()->width()) { painter.drawPixmap(m_offset + m_pixmap.width(), 0, m_pixmap); }} m_pixmap好像没有定义
时间: 2024-03-27 10:40:43 浏览: 60
CustomHeader:在 QTableView 中使用 QComboBox 自定义 QHeaderView
是的,你是正确的。在这段代码中,确实没有定义m_pixmap。你可以在类的构造函数中初始化它,或者在需要绘制图片之前加载它。例如,你可以添加以下代码:
```cpp
CustomScrollArea::CustomScrollArea(QWidget *parent) : QScrollArea(parent), m_offset(0) {
// 设置水平滚动条不可见
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// 设置垂直滚动条不可见
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// 设置背景色为白色
setStyleSheet("background-color:white;");
// 加载图片
m_pixmap = QPixmap("your_image_path_here");
}
```
请确保替换"your_image_path_here"为你的图片路径。
阅读全文