【问题标题】:Select tab text in QTabBar在 QTabBar 中选择标签文本
【发布时间】:2020-10-01 23:34:59
【问题描述】:

如何使用鼠标选择QTabBar 中的选项卡文本?

QLabel 中的文本可以按照此处所述选择:Make QLabel text selectable?,但我还没有找到类似的方法来为 QTabBar 选项卡文本执行此操作。

QTabBar 的文档可在此处找到:https://doc.qt.io/qt-5/qtabbar.html。它多次提到“选择”,但这些实例都与选择文本无关。相反,它们都与选择标签本身有关。

【问题讨论】:

  • 可以this thread 有什么帮助吗?..
  • 查看 QTabBar 和 QTabWidget 的源代码,选项卡似乎没有通过 QLabel 显示它们的文本,并且绝对不会像 QLabel 那样暴露交互标志。

标签: c++ qt


【解决方案1】:

Qt 本身并不建议使QTabBar 文本可选。

但是,它们允许您使用 QTabBar::setTabButton 将自己的小部件添加到选项卡本身。然后,您可以创建没有标题的选项卡 (""),然后添加带有您的标题的 QLabel 并使其可选。 请注意,单击 QLabel 本身不会更改当前选项卡,您需要手动处理(在下面的示例代码中完成)。

这是一个有效的示例代码(可以选择活动和非活动选项卡的文本):

#include <QApplication>
#include <QMainWindow>
#include <QTabWidget>
#include <QTabBar>
#include <QLabel>

#include <map>

class MainFrame : public QMainWindow
{
public:
    MainFrame()
    {
        tabWidget = new QTabWidget( this );
        setCentralWidget( tabWidget );

        addSelectableTab( new QLabel( "Hello World", tabWidget ), "foo" );
        addSelectableTab( new QLabel( "Hello World", tabWidget ), "bar" );
    }

    void addSelectableTab( QWidget* widget, const QString& title )
    {
        int index = tabWidget->addTab( widget, "" );

        QLabel* titleLabel = new QLabel( title );
        titleLabel->setTextInteractionFlags( Qt::TextSelectableByMouse );
        tabWidget->tabBar()->setTabButton( index, QTabBar::RightSide, titleLabel );

        tabLabels[titleLabel] = index;
        titleLabel->installEventFilter( this );
    }

    bool eventFilter(QObject *obj, QEvent *event) override
    {
        /** When using QLabel as tab title, current tab can only be changed by clicking outside
         *  the label...so let's detect when user clicked inside the label and then change current tab!
         */
        if ( event->type() == QEvent::MouseButtonRelease )
        {
            auto found = tabLabels.find( dynamic_cast<QLabel*>( obj ) );
            if ( found != tabLabels.end() )
            {
                if ( !found->first->hasSelectedText() )
                {
                    // suppose user clicked the label
                    tabWidget->setCurrentIndex( found->second );
                    return true;
                }
            }
        }

        return QMainWindow::eventFilter( obj, event );
    }

private:
    QTabWidget* tabWidget;

    // this is to know what tab should be activated when a label is clicked
    // you may get rid of that by using QTabBar::tabButton to identify what
    // tab a QLabel is related to
    std::map<QLabel*,int> tabLabels;
};

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

    MainFrame wnd;
    wnd.show();
    return app.exec();
}

现在可以选择标签标题:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多