在Qt上滚动标签列表

Scrolling list of labels on Qt

本文关键字:标签 列表 滚动 Qt      更新时间:2023-10-16

我正试图为我的标签创建一个滚动条。目前,如果用户创建了太多标签,按钮和文本区域的大小就会减小,这就是为什么我想创建一个滚动条,那么如果标签太多,他们就不会改变窗口的外观。

这是我的实际代码:

#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小部件类。通过关闭文本交互标志、框架样式和未设置的背景色,您基本上将获得可滚动的QLabel

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