Qt 上的滚动标签列表

Scrolling list of labels on Qt

我正在尝试为我的标签创建一个滚动条。目前,如果用户创建太多标签,按钮和文本区域的大小会减小,这就是为什么我想创建一个滚动条,如果标签太多,它们不会改变 window.

这是我的实际代码:

#include <iostream>
#include <QApplication>
#include <QPushButton>
#include <QLineEdit>
#include <QWidget>
#include <QFormLayout>
#include "LibQt.hpp"

LibQt::LibQt() : QWidget()
{
  this->size_x = 500;
  this->size_y = 500;
  QWidget::setWindowTitle("The Plazza");
  setFixedSize(this->size_x, this->size_y);
  manageOrder();
}

LibQt::~LibQt()
{
}

void LibQt::keyPressEvent(QKeyEvent* event)
{
  if (event->key() == Qt::Key_Escape)
    QCoreApplication::quit();
  else
    QWidget::keyPressEvent(event);
}

void LibQt::manageOrder()
{
  this->converLayout = new QFormLayout;
  this->testline = new QLineEdit;
  this->m_button = new QPushButton("Send");
  this->m_button->setCursor(Qt::PointingHandCursor);
  this->m_button->setFont(QFont("Comic Sans MS", 14));
  this->converLayout->addRow("Order : ", this->testline);
  this->converLayout->addWidget(this->m_button);
  QObject::connect(m_button, SIGNAL(clicked()), this, SLOT(ClearAndGetTxt()));
  CreateLabel("test");
  CreateLabel("test2");
}

void            LibQt::CreateLabel(std::string text)
{
  QString qstr = QString::fromStdString(text);

  this->label = new QLabel(qstr);
  this->converLayout->addWidget(this->label);
  this->setLayout(converLayout);
}

std::string     LibQt::ClearAndGetTxt()
{
  QString txt = this->testline->text();

  if (!txt.isEmpty())
    {
      this->usertxt = txt.toStdString();
      std::cout << this->usertxt << std::endl;
      this->testline->clear();
      CreateLabel(this->usertxt);
      return (this->usertxt);
    }
  return (this->usertxt);
}

std::string     LibQt::getUsertxt()
{
  return (this->usertxt);
}

这是 .hpp 文件:

#ifndef _LIBQT_HPP_
#define _LIBQT_HPP_

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QKeyEvent>

class   LibQt : public QWidget
{
  Q_OBJECT

public:
  LibQt();
  ~LibQt();
  void manageOrder();
  std::string getUsertxt();
  void keyPressEvent(QKeyEvent *event);
  void keyPressEventEnter(QKeyEvent *event);
  void CreateLabel(std::string text);
public slots:
  std::string ClearAndGetTxt();
protected:
  int   size_x;
  int   size_y;
  QPushButton *m_button;
  QLineEdit *testline;
  std::string usertxt;
  QLabel *label;
  QFormLayout *converLayout;
};

#endif /* _LIBQT_HPP_ */

有不同的解决方案,具体取决于您想要什么

  1. QTextEdit 是用于可滚动文本的 Qt 小部件 class。通过关闭文本交互标志、框架样式和取消设置背景颜色,您基本上可以滚动 QLabel

  2. QScrollArea 作为更通用的解决方案