【问题标题】:how to align text of table widget in QT如何在 QT 中对齐表格小部件的文本
【发布时间】:2015-09-28 21:07:49
【问题描述】:

在我的应用程序中,我有表格小部件,我想为表格中的所有单元格设置文本对齐中心。为此,我尝试过,

 QTableWidgetItem * protoitem = new QTableWidgetItem();
 protoitem->setTextAlignment(Qt::AlignRight);
 tableWidget->setItemPrototype(protoitem);

但它无法正常工作,请指导我,

【问题讨论】:

标签: c++ qt


【解决方案1】:

您需要使用委托来完成此操作。使用以下内容覆盖代表paint 事件:

QAlignmentDelegate.h

#include <QStyledItemDelegate>

class QAlignmentDelegate : public QStyledItemDelegate
{
public:

    explicit QAlignmentDelegate(Qt::Alignment alignment, QObject* parent = 0)
    : QStyledItemDelegate(parent),
    m_alignment(alignment)
    {

    }

    virtual void QAlignmentDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        QStyleOptionViewItem alignedOption(option);
        alignedOption.displayAlignment = m_alignment;
        QStyledItemDelegate::paint(painter, alignedOption, index);
    }

private:

    Qt::Alignment   m_alignment;                                                                    ///< Stores the alignment to use

};

然后简单地将委托分配给视图。在您的mainWindow 类(或您创建或使用视图的任何位置)中,可以按如下方式使用委托:

主窗口代码

#include "QAlignmentDelegate.h"
...


QAlignmentDelegate* myDelegate = new QAlignmentDelegate(Qt::AlignmentCenter);
QTableView* myTableView = new QTableView(this);
myTableView->setItemDelegate(myDelegate);
myTableView->setModel(...); // start using the view

您可以在创建委托时指定任何 Qt::Alignment(或使用 OR 组合它们)。

或者,如果您编写/控制模型代码,您可以实现 Qt::AlignmentRole 并返回 'Qt::AlignHCenter 以获得您想要对齐的数据。

【讨论】:

  • 我是新手,所以无法实施。能不能用“tableWidget”改一下代码,让我理解得很好
  • @sivanesan 我添加了一个如何创建委托并将其附加到视图的示例。
  • @sivanesan 好的,然后继续更新您的问题
  • @sivanesan 那行不通。你不能随意决定不继承QStyledItemDelegate。完全按照我给你的方式使用我的委托。
  • :经过长时间的努力,我取得了成功,但样式表现在不起作用
猜你喜欢
  • 1970-01-01
  • 2018-11-08
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多