gpt4 book ai didi

QTableWidget 中的 Qt MouseTracking

转载 作者:行者123 更新时间:2023-12-04 13:04:26 27 4
gpt4 key购买 nike

我想使用 Qt4.7 在 QTableWidget 中启用 mouseTracking。通常这应该直接使用 setMouseTracking(true)。这适用于其他小部件,但 QTableWidget 抵制它。为了激活 mouseTracking,我需要处理什么特别的事情吗?

虽然我实际上正在做更复杂的事情,但我可以确信它没有通过在 mouseMoveEvent 中打印出 QMouseEvent.x() 来启用。到目前为止谢谢:)

这是我尝试过的:

    QGridLayout * layout = new QGridLayout(this);
SCTableWidget * aTable = new SCTableWidget(tableRows, tableCols, this);

QTableWidgetItem * newItem;
for(int i = 0; i<(3); i++) {
for(int j = 0; j<(17); j++) {
newItem = new QTableWidgetItem(QString::number(tableData[i][j]));
aTable->setItem(i,j, newItem);
}
}

// First try
aTable->setMouseTracking(true);

//Second try. Main Window further down.
MainWindow::instance->enableMouseTracking(aTable->children());
MainWindow::instance->enableMouseTracking(aTable->viewport()->children());


// Third try
aTable->viewport()->setMouseTracking(true);

layout->addWidget(aTable, 0, 0, 1, 2);

第二次尝试包含一个在 MainWindow 中实现的方法,如下所示:

void
MainWindow::enableMouseTracking(const QObjectList & pChildren)
{
foreach(QObject * obj, pChildren)
{
QWidget * w = qobject_cast<QWidget *>(obj);

if(w)
{
w->setMouseTracking(true);
enableMouseTracking(w->children());
}
}
}

最佳答案

为 QTableWidget->viewport() 打开鼠标跟踪通常是有效的。您是否也在为 QTableWidget->viewport() 小部件捕获鼠标事件?请检查以下示例是否适合您:

测试.h:

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

bool eventFilter(QObject *obj, QEvent *event);

private:
Ui::MainWindow *ui;
QTableWidget *table;
};

测试.cpp:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

table = new QTableWidget(5, 10, this);
table->setGeometry(10, 20, 300, 200);

for (int row=0; row<5; ++row)
for (int column=0; column<10; ++column)
table->setItem(row, column, new QTableWidgetItem(tr("%1").arg((row+1)*(column+1))));

table->setMouseTracking(true);
table->viewport()->setMouseTracking(true);
table->installEventFilter(this);
table->viewport()->installEventFilter(this);
}

MainWindow::~MainWindow()
{
delete ui;
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == table)
{
if (event->type() == QEvent::MouseButtonPress)
qDebug() << "table mouse press event";
else if (event->type() == QEvent::MouseMove)
qDebug() << "table mouse moveevent";
}
else if (obj == table->viewport())
{
if (event->type() == QEvent::MouseButtonPress)
qDebug() << "table->viewport mouse press event";
else if (event->type() == QEvent::MouseMove)
qDebug() << "table->viewport mouse moveevent";
}
return QMainWindow::eventFilter(obj, event);
}

希望这对你有帮助,问候

关于QTableWidget 中的 Qt MouseTracking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4800643/

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