gpt4 book ai didi

c++ - 如何在QT中对齐表格小部件的文本

转载 作者:行者123 更新时间:2023-11-28 06:03:34 26 4
gpt4 key购买 nike

In my application , im having table widget , i want to set the text alignment center for all the cells in the table. For that i tried like,

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

but it not working properly, guide me,

最佳答案

您需要使用委托(delegate)来完成此操作。用以下内容覆盖委托(delegate) 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

};

然后只需将委托(delegate)分配给 View 即可。在您的 mainWindow 类(或您创建或使用 View 的任何地方)中,委托(delegate)可以按如下方式使用:

主窗口代码

#include "QAlignmentDelegate.h"
...


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

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

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

关于c++ - 如何在QT中对齐表格小部件的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32822442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com