layout

__040711563a17902392e7

海前 王

Posted on September 13, 2024

layout
#include <QApplication>
#include <QMainWindow>
#include <QListView>
#include <QStandardItemModel>
#include <QVBoxLayout>
#include <QLabel>
#include <QTransform>
#include <QPainter>

class VerticalLabel : public QLabel
{
public:
    VerticalLabel(const QString &text, QWidget *parent = nullptr) : QLabel(text, parent)
    {
        setAlignment(Qt::AlignCenter);
    }

protected:
    void paintEvent(QPaintEvent *event) override
    {
        QPainter painter(this);
        QTransform transform;
        transform.rotate(-90); // 旋转90度
        painter.setTransform(transform);
        painter.drawText(-height(), 0, height(), width(), alignment(), text());
    }

    QSize sizeHint() const override
    {
        QSize s = QLabel::sizeHint();
        return QSize(s.height(), s.width()); // 交换宽高
    }
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent)
    {
        setWindowTitle("QListView Example");
        resize(400, 300);

        // 创建数据模型
        QStandardItemModel *model = new QStandardItemModel;
        QStringList fileList = {"File1.txt", "File2.txt", "File3.txt", "File4.txt"};

        for (const QString &file : fileList) {
            QStandardItem *item = new QStandardItem(file);
            model->appendRow(item);
        }

        // 创建列表视图
        QListView *listView = new QListView;
        listView->setModel(model);
        listView->setViewMode(QListView::ListMode); // 设置视图模式为列表模式
        listView->setSelectionMode(QAbstractItemView::SingleSelection); // 设置选择模式为单选
        listView->setSpacing(5); // 设置项目间距

        // 创建垂直标签
        VerticalLabel *titleLabel = new VerticalLabel("File List");

        // 布局管理
        QHBoxLayout *layout = new QHBoxLayout;
        layout->addWidget(listView);
        layout->addWidget(titleLabel); // 将标题放在右侧

        QWidget *centralWidget = new QWidget;
        centralWidget->setLayout(layout);
        setCentralWidget(centralWidget);
    }
};

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

    // 创建主窗口并显示
    MainWindow mainWindow;
    mainWindow.show();

    return app.exec();
}

#include "main.moc"
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
__040711563a17902392e7
海前 王

Posted on September 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related